
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Default Parameter Values to a Function in Python
Python functions are used to implement logic that you may want to reuse in multiple places in your code. These functions accept input parameters called arguments. You can also assign default values to these parameters.
If you do not pass any value for a parameter during a function call, the default value will be used automatically. Default values are assigned using the assignment operator (=) in the format param=value.
The syntax representation and default values for function parameters are different in Python. If no argument value is given during the function call, the default values mean that the function parameter will assume that value. By employing the assignment(=) operator with the syntax keywordname=value, the default value is set.
What is a Function in Python?
A function is a block of code that executes only when it is called. You can pass data to functions using arguments, and functions can return results.
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 output generated is as follows -
Hello World
Arguments in a Function in Python
Functions accept values known as arguments, which are passed into the function when it is called. These arguments correspond to parameters, the variables listed inside the parentheses in the function definition. You can define a function with one or more parameters by separating them with commas.
What is a Default Parameter?
A default parameter is a function argument that uses a predefined value if no argument is passed during the function call. Default values help your functions prevent raising errors when optional arguments are not provided.
Syntax
Following is the basic syntax to set default parameter values -
def function_name(param1=value1, param2=value2, ...): # function body
Use the assignment operator (=) to set a default value. Parameters with default values must appear after parameters without default values.
Example
Let us look at a simple Python function as an example that uses a default argument -
def greet(name="world"): print("Hello,", name) greet()
The output generated is as follows -
Hello, world
Example: Single Default Argument
Let us create a function that has a single default argument.
The script defines the function find square() with a single integer as the default argument. The integer argument's default value is set to 2. The cube of a value passed as the integer argument to the find cube() method's call will be returned by the function.
Otherwise, the default value, 2, will be assigned to the integer argument of the find square() function, and the function will return the square of 2, which is 8. If you do not pass any value for the integer argument of the find cube() function, you will observe that.
Let's initially use the argument value of 10 to call the find cube() method -
def find_cube(integer1=2): result = integer1 * integer1 * integer1 return result result= find_cube(10) print(result)
The output generated is as follows -
1000
Mutable Default Argument Issue
Using mutable objects like lists as default values can lead to unexpected behavior because the same object is reused across function calls.
Example
In the example below, func() uses the same list every time it is called because the default argument is a mutable list. This can lead to unexpected results. On the other hand, append2() function creates a new list each time if no list is given, so each call works independently -
def func(data=[]): data.append(1) return data func() func() def append2(element, foo=None): if foo is None: foo = [] foo.append(element) return foo print(append2(12)) print(append2(43))
The output generated is as follows -
[12] [43]
Incorrect Example Using Mutable Default
Here, the function keeps using the same list for every call because of the mutable default data=[], so values keep getting added to the same list -
def append_once(element, data=[]): data.append(element) return data print(append_once(1)) print(append_once(2))
The result obtained is -
[1] [1, 2]
Correct Way to Handle Mutable Defaults
This function creates a new list each time by checking if data is None, so the elements don't get added to the same list across calls -
def append_safely(element, data=None): if data is None: data = [] data.append(element) return data print(append_safely(1)) print(append_safely(2))
Following is the output obtained -
[1] [2]
Calling functions without Keyword Arguments
In this section, we will learn how to call a function with or without providing a value for its parameters. If no value is passed, the function will use its default value.
Example
The following function works even if no argument is provided because a name has a default value -
def greet(name="world"): print("Hi", name) greet() greet("Rohan")
We get the output as shown below -
Hi world Hi Rohan
Calling Functions with Keyword Arguments
Keyword arguments are used to directly assign values to specific parameters in a function. It also allows you to change the order of parameters or skip some of them without causing any errors.
With keyword arguments, you can choose to set values for only some parameters, and the rest will automatically use their default values if not specified.
Example
In the following example, we are defining a function with default values for the parameters. The function is then called three times, each time using different values for the parameters, either leaving them as default or changing one or both.
def describe_pet(animal="dog", name="Buddy"): print(f"I have a {animal} named {name}.") describe_pet() describe_pet(name="Charlie") describe_pet(animal="cat", name="Misty")
Following is the output of the above code -
I have a dog named Buddy. I have a dog named Charlie. I have a cat named Misty.
Invalid Function Definition
You cannot place a non-default argument after a default one. Parameters with default values must come last, otherwise it will throw an error as shown in the example below -
# ? This will raise a SyntaxError def invalid_func(name="John", age): print(name, age)
We get the following error -
SyntaxError: parameter without a default follows parameter with a default
Multiple Default Parameters
You can define multiple parameters with default values. All such parameters must appear after the required parameters.
Example
The default arguments for the function would be 12 and 4, respectively, if either of the integer values were omitted, as illustrated below.
def add_integers(int1=12, int2=4): result = int1 + int2 return result result = add_integers() print(result)
The output generated is as follows -
16