Default Arguments in Python
In Python, we can assign a default value to a function parameter. This means if the caller does not provide a value for that argument, the default value will be used.
Default arguments make our functions flexible and easy to use, especially when some values are optional.
Syntax:
def function_name(param1, param2=default_value):
# code
...
Here, param2 has a default value. If the user doesn’t pass it, Python
uses the default.
Example 1: One argument with default value
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Angel")
Output:
Hello, Guest
Hello, Angel
Explanation:
- When
greet()is called without arguments, it uses the default"Guest". - When
greet("Angel")is called, it overrides the default and prints the custom name.
Example 2: Function with multiple default arguments
def info(name="User", age=18):
print("Name:", name)
print("Age:", age)
info()
info("Mukesh", 21)
Output:
Name: User
Age: 18
Name: Mukesh
Age: 21
Explanation:
- In the first call, no arguments are passed — so both defaults are used.
- In the second call, both arguments are provided — so those are used instead.
Important Rule:
Default arguments should always come after non-default arguments.
Invalid Example:
# ❌ Wrong way
def greet(name="Guest", age):
print(name, age)
This will give an error because a default argument cannot appear before a required argument.
Summary:
- Default arguments provide fallback values in case no argument is passed.
- They make function calls simpler and shorter.
- Default values are defined in the function header.
- Non-default parameters must always come before default ones.