How to pass optional parameters to a function in Python?
Last Updated :
12 Mar, 2025
In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primary ways to pass optional parameters:
- Without using keyword arguments
- By using keyword arguments
Both methods allow flexibility in function calls, but they have different rules regarding the order of parameters and argument passing.
Passing without using keyword arguments
When passing optional parameters without explicitly mentioning their names, certain rules must be followed:
- The order of parameters must be maintained.
- All required (non-optional) parameters must be provided.
- The optional parameters can be either provided or omitted (in which case their default values are used).
Example 1: Using default values
Python
def fun(a, b=1098):
return a + b
print(fun(2, 2)) # Passing both parameters
print(fun(1)) # 'b' takes the default value 1098
Explanation: fun(a, b=1098) takes two parameters a and b, where b has a default value of 1098. When both arguments are provided, the function returns their sum. If only a is passed, b takes its default value and their sum is returned.
Example 2: Default parameter with strings
Python
def fun(a, b="Geeks"):
print(a + b)
fun('GeeksFor') # Uses the default value of 'b'
fun('GeeksFor', "Hub") # Provides a different value for 'b'
OutputGeeksForGeeks
GeeksForHub
Explanation: fun(a, b=”Geeks”) takes two parameters a and b, where b defaults to “Geeks”. It prints the concatenation of a and b. If both arguments are provided, it prints their combined value otherwise, b takes its default value.
Passing with keyword arguments
Python allows function calls to explicitly specify parameter names when passing arguments. This has certain advantages:
- The order of arguments does not need to be maintained.
- Only required parameters must be passed , optional ones can be omitted.
- The parameter names must match exactly as declared in the function.
Example 1: Using keyword arguments
Python
def fun(a,b="Geeks"):
print(a + b)
# Passing arguments without maintaining order
fun(a='ForGeeks', b="Geeks")
Explanation: fun(a, b=”Geeks”) takes two parameters a and b, where b defaults to “Geeks”. It prints their concatenation. Here, both arguments are explicitly passed using keywords, ensuring correct assignment.
Example 2: Keyword arguments with mixed data types
Python
def fun(a, b, c='geeks'):
print(a, "type is", type(a))
print(b, "type is", type(b))
print(c, "type is", type(c))
fun(2, 'z', 2.0) # All arguments passed explicitly
fun(2, 1) # Default value of 'c' used
fun(c=2, b=3, a='geeks') # Keyword arguments change order
Output
2 type is <class 'int'>
z type is <class 'str'>
2.0 type is <class 'float'>
2 type is <class 'int'>
1 type is <class 'int'>
geeks type is <class 'str'>
geeks type is <class 'str'>
3 type is <class 'int'>
Explanation: fun(a, b, c=’geeks’) takes three parameters, with c defaulting to ‘geeks’. It prints each argument along with its type. Arguments can be passed explicitly, use the default value or be reordered using keyword arguments.
Combining positional and keyword arguments
We can use both positional and keyword arguments in the same function call, but positional arguments must come before keyword arguments.
Example: Positional and Keyword Arguments Together
Python
def fun(a, b=2):
if a < b:
print("First smaller")
elif a > b:
print("Second smaller")
else:
print("Equal")
fun(1) # Default 'b' used
fun(2, 1) # Both parameters passed
fun(b=1, a=-1) # Keyword arguments change order
fun(-1, b=0) # Positional and keyword arguments combined
OutputFirst smaller
Second smaller
First smaller
First smaller
Explanation: fun(a, b=2) compares a and b, printing whether the first is smaller, the second is smaller or both are equal. It works with default, positional, keyword and mixed arguments.
How to pass optional parameters to a function in Python? – FAQs
How to pass optional parameters in Python function?
To pass optional parameters in a Python function, you can define default values for parameters in the function definition. This allows the function to be called with fewer arguments than defined.
How to give an optional parameter to a function?
An optional parameter is given to a function by assigning it a default value in the function definition. For example:
def example_function(param1, optional_param=None):
# Function body
In this case, optional_param is optional and defaults to None if not provided.
How to pass extra arguments to a function in Python?
You can pass extra arguments to a function using *args for positional arguments and **kwargs for keyword arguments. This allows the function to accept an arbitrary number of additional arguments.
How to skip positional arguments in Python?
Skipping positional arguments in a function call can be achieved by using keyword arguments. This way, you can specify only the arguments you want to pass, and the rest will use their default values.
def example_function(a, b=2, c=3):
# Function body
example_function(a=1, c=4) # b uses its default value of 2
What does args mean in Python?
*args in a function definition allows the function to accept a variable number of positional arguments. Inside the function, args is a tuple containing all the positional arguments passed. It is used when you want to create functions that can handle an arbitrary number of positional arguments.
Similar Reads
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
Python def Keyword
Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the âdefâ keyword. In Python def
6 min read
Difference between Method and Function in Python
Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d
3 min read
First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Assign Function to a Variable in Python
In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
4 min read
User-Defined Functions
Python User Defined Functions
A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency. Example: [GFGTABS] Python # function de
6 min read
Python User Defined Functions
A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency. Example: [GFGTABS] Python # function de
6 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Defining a Python Function at Runtime
One amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. Itâs especially useful for things like metaprogramming, event-driven systems and running code dynamically
3 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Explicitly define datatype in a Python function
Unlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to
4 min read
Built-in and Special Functions
Global and Local Variables
Parameters and Arguments
Python Function Parameters and Arguments
Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
Keyword and Positional Argument in Python
Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call. Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Ke
4 min read
How to find the number of arguments in a Python function?
Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones. Using in
4 min read
Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argu
7 min read
Passing function as an argument in Python
In Python, functions are first-class objects meaning they can be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, decorators and lambda expressions. By passing a function as an argument, we can modify a functionâs behavior dynamically
6 min read
How to get list of parameters name from a function in Python?
The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a,
4 min read
How to pass optional parameters to a function in Python?
In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Return Statements
How to pass optional parameters to a function in Python?
In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
Python None Keyword
None is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. C/C++ Code def check_return(): pass print(c
2 min read
Returning a function from a function - Python
In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior. Example: [GFGTABS] Python def fun1(name): def fun2(): return f"Hello, {name}!"
5 min read