How to pass optional parameters to a function in Python?

PythonProgrammingServer Side Programming

A type of argument with a default value is a Python optional parameter. A function definition's assignment operator or the Python **kwargs statement can be used to assign an optional argument. Positional and optional arguments are the two sorts of arguments that a Python function can take. Values that are not required to be given in order to call a function are known as optional parameters.

Function in Python

A function is a section of code that only executes when called. You can supply parameters that is data to a function. As a result, a function may or may not return data.

Example

Let us understand what a function in python is with the help of an example.

def demo_function(): print("Hello World") demo_function() #the demo_function() method is called.

Output

The output obtained is as follows.

Hello World

Arguments in a Function

Functions accept arguments that can contain data. The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like. The function in the following example only takes one argument (fname). A first name is passed to the function when it is called, and it is utilized there to print the whole name.

Optional Arguments in Python

An argument in Python that has a default value is called an optional argument. A default value for an argument can be specified using the assignment operator. When calling a function, there is no requirement to provide a value for an optional argument. This is because, in the absence of a value, the default value will be used.

Argument default values are possible. This renders an argument unnecessary. If a default value is present for an argument, it will be used if no alternative value is provided.

Python has two primary methods for passing optional parameters. They are as follows.

  • Without utilizing keyword justifications.

  • Use keyword justifications.

Passing without using keyword arguments

The following are some major considerations when passing without keyword arguments −

  • When invoking a function, the order of the parameters—that is, the order in which the parameters are defined in the function—should be preserved.

  • The non-optional arguments' values must be provided otherwise an error will be thrown.

  • The default argument value can either be supplied or disregarded.

Example

Let’s look at an example to see how optional arguments are passed.

# Python program to demonstrate a optional argument. def function(a, b=999): return a+b print(function(2, 3)) # In the function 1 is represented as 'a' in the function and #The function uses the default value of b print(function(1))

Output

The following is the output that is generated upon executing the above program.

5
1000
raja
Updated on 16-Sep-2022 07:40:14

Advertisements