In Python, functions can have default arguments, which are parameters with predefined values. This means you don’t always need to pass every argument while calling a function.
- If you provide a value, Python uses it.
- If you skip it, the default value is used automatically.
Example: Here's a simple example that shows how default arguments work.
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Kate")
Output
Hello, Guest Hello, Kate
Explanation:
- In the first call greet(), no argument is passed, so Python uses the default value "Guest".
- In the second call greet("Kate"), the default value is overridden with "Kate".
Syntax of Default Arguments
def function_name(param1=value1, param2=value2, ...):
# function body
Parameters:
- param1, param2, ...: Names of the parameters.
- value1, value2, ...: Default values assigned using =.
- function_name: The name of the function.
Rules to Keep in Mind
- Non-default parameters must come before default parameters in the function definition.
- Positional arguments must come before keyword arguments when calling a function.
- If using keyword arguments, order does not matter.
- Each parameter must have only one value.
- Keyword name must match exactly with the function definition.
- For positional (non-keyword) arguments, order matters strictly.
Examples
Example 1: This example shows how default values work when a function is called with positional arguments. If some arguments are not provided, their defaults are used.
def student(fn, ln='Mark', std='Fifth'):
print(fn, ln, 'studies in', std, 'Standard')
student('John')
student('John', 'Gates', 'Seventh')
student('John', 'Gates')
student('John', 'Seventh')
Output
John Mark studies in Fifth Standard John Gates studies in Seventh Standard John Gates studies in Fifth Standard John Seventh studies in Fifth Standard
Explanation: 'fn' is required, while ln and std use defaults if not provided. Order matters in positional arguments.
Example 2: This example demonstrates calling a function using keyword arguments. It allows passing values by parameter names and in any order.
def student(fn, ln='Mark', std='Fifth'):
print(fn, ln, 'studies in', std, 'Standard')
student(fn='John')
student(fn='John', std='Seventh')
student(ln='Gates', fn='John')
Output
John Mark studies in Fifth Standard John Mark studies in Seventh Standard John Gates studies in Fifth Standard
Explanation: Keyword arguments allow assigning values by name, and order does not matter.
Example 3: This example highlights mistakes when mixing positional, keyword or missing arguments.
def student(fn, ln='Mark', std='Fifth'):
print(fn, ln, 'studies in', std, 'Standard')
student()
student(fn='John', 'Seventh')
student(sub='Maths')
Explanation: This code raises errors because 'fn' is missing, positional is placed after keyword and sub is not a valid parameter.
Example 4: This example shows the problem of using a list as a default argument. The same list is reused across calls.
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item('note'))
print(add_item('pen'))
print(add_item('eraser'))
Output
['note'] ['note', 'pen'] ['note', 'pen', 'eraser']
Explanation: The same list lst is reused, so items keep accumulating.
Example 5: This example shows the same problem when using a dictionary as a default argument.
def add_dict(item, qty, d={}):
d[item] = qty
return d
print(add_dict('note', 4))
print(add_dict('pen', 1))
print(add_dict('eraser', 1))
Output
{'note': 4}
{'note': 4, 'pen': 1}
{'note': 4, 'pen': 1, 'eraser': 1}
Explanation: The same dictionary d is reused, so all items are stored together.
Example 6: This example shows the correct way use None as the default and create a new list or dictionary inside the function.
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
print(add_item('note'))
print(add_item('pen'))
print(add_item('eraser'))
def add_dict(item, qty, d=None):
if d is None:
d = {}
d[item] = qty
return d
print(add_dict('note', 4))
print(add_dict('pen', 1))
print(add_dict('eraser', 1))
Output
['note']
['pen']
['eraser']
{'note': 4}
{'pen': 1}
{'eraser': 1}
Explanation: Each time the function is called without arguments, a new list or dictionary is created. This prevents sharing between calls.