Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Pass Optional Parameters to a Function in Python



In Python, you can pass optional parameters to functions, allowing you to call a function with fewer arguments than specified. Optional parameters are useful for providing default values when certain arguments are not provided.

Python provides different ways to define optional parameters, including default values, variable-length argument lists, and keyword arguments.

Using Default Arguments

One common way to pass optional parameters is by setting default values for the parameters in the function definition. If no argument is passed for those parameters during the function call, the default value is used.

Example

In the following example, the greet() function has an optional name parameter with a default value of "Guest" -

def greet(name="Guest"):
   print(f"Hello, {name}!")

greet("Rohan")
greet()  # Uses default value

We get the following output -

Hello, Rohan!
Hello, Guest!

Without Using Keyword Arguments

You can pass optional parameters without using keyword arguments by providing default values. When calling the function, the parameters can either be omitted (using the default value) or specified by position.

Example

Here is an example where we define a function with default parameters and call it without using keyword arguments -

def greet(name="Guest", age=18):
   print(f"Hello, {name}! You are {age} years old.")

# Without keyword arguments
greet("Rohan", 25)  
# Uses default value for age
greet("Geet")  
# Uses default values for both parameters
greet()  

Following is the output obtained -

Hello, Rohan! You are 25 years old.
Hello, Geet! You are 18 years old.
Hello, Guest! You are 18 years old.

By Using Keyword Arguments

Alternatively, you can use keyword arguments to pass optional parameters. This allows you to specify values for specific parameters, irrespective of their position in the function call.

Example

In this example, we use keyword arguments to pass optional parameters explicitly -

def greet(name="Guest", age=18):
   print(f"Hello, {name}! You are {age} years old.")

# Using keyword arguments
greet(age=25, name="Rohan")  
# Uses default value for name
greet(age=30) 
# Uses default values for both parameters
greet()  

We get the following output -

Hello, Rohan! You are 25 years old.
Hello, Guest! You are 30 years old.
Hello, Guest! You are 18 years old.

Using *args for Variable Number of Positional Arguments

In Python, you can also pass a variable number of positional arguments using *args. This allows you to pass a variable number of arguments to a function. It is useful when you don't know how many arguments you will pass.

Example

In the example below, we define a function that accepts any number of arguments and prints them -

def display(*args):
   for arg in args:
       print(arg)

display("apple", "banana", "cherry")
display("dog", "cat")  # More or fewer arguments can be passed

Following is the output of the above code -

apple
banana
cherry
dog
cat

Using **kwargs for Variable Number of Keyword Arguments

Similar to *args, you can use **kwargs to pass a variable number of keyword arguments.

This allows you to pass arguments in the form of key-value pairs, where each key represents a parameter name and the corresponding value represents the argument passed for that parameter.

Example

In the following example, we define a function that accepts any number of keyword arguments and prints each key-value pair -

def show_details(**kwargs):
   for key, value in kwargs.items():
       print(f"{key}: {value}")

show_details(name="Rohan", age=25, city="India")
show_details(language="Python", version=3.9)  # More or fewer keyword arguments

We get the output as shown below -

name: Rohan
age: 25
city: India
language: Python
version: 3.9

Combining Default Parameters with *args and **kwargs

Python allows you to combine default parameters, *args, and **kwargs in a single function definition. The order in which they appear is important: default parameters come first, followed by *args, and finally **kwargs.

Example

In this example, the function accepts both optional positional arguments and optional keyword arguments -

def profile(name, age=18, *args, **kwargs):
   print(f"Name: {name}, Age: {age}")
   print("Hobbies:", args)
   for key, value in kwargs.items():
       print(f"{key}: {value}")

profile("Rohan", 25, "Reading", "Traveling", occupation="Engineer", city="India")

We get the following output -

Name: Rohan, Age: 25
Hobbies: ('Reading', 'Traveling')
occupation: Engineer
city: India

Using None as a Default Value

Another way to create optional parameters is by using None as the default value. This can be useful if you want to check whether the argument was passed or not, allowing you to handle cases where no value is provided.

Example

In this example, the function checks if the argument is None before taking action -

def greet(name=None):
   if name is None:
       print("Hello, Guest!")
   else:
       print(f"Hello, {name}!")

greet("Rohan")
greet()  # Uses None as default

The result obtained is as shown below -

Hello, Rohan!
Hello, Guest!
Updated on: 2025-05-15T12:55:05+05:30

52K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements