![]() |
VOOZH | about |
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.
Example: Here's a simple example that shows how default arguments work.
Hello, Guest Hello, Kate
Explanation:
def function_name(param1=value1, param2=value2, ...):
# function body
Parameters:
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.
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.
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.
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.
['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.
{'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.
['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.