Recall & Review
beginner
What are default arguments in Python functions?
Default arguments are values given to function parameters that are used if no argument is provided when the function is called.
Click to reveal answer
beginner
How do you define a default argument in a Python function?
You assign a value to a parameter in the function definition, like
def greet(name='Friend'):.Click to reveal answer
beginner
What happens if you call a function with a default argument but provide a value for that argument?
The provided value overrides the default argument value for that call.
Click to reveal answer
intermediate
Why should mutable objects be avoided as default argument values?
Because the same mutable object is shared across calls, which can cause unexpected behavior if it is modified.
Click to reveal answer
intermediate
Example: What is the output of this code?
def add_item(item, item_list=[]):
item_list.append(item)
return item_list
print(add_item('apple'))
print(add_item('banana'))Output:
This happens because the default list is shared between calls.
['apple'] ['apple', 'banana']
This happens because the default list is shared between calls.
Click to reveal answer
What is the correct way to set a default argument for a function parameter in Python?
✗ Incorrect
Default arguments are set by assigning a value in the function definition, like
def func(x=10):.If a function has a default argument, what happens when you call it without that argument?
✗ Incorrect
When a default argument is not provided in the call, Python uses the default value.
Why can using a mutable object like a list as a default argument cause problems?
✗ Incorrect
Mutable default arguments are shared between calls, so changes persist and can cause bugs.
How can you avoid issues with mutable default arguments?
✗ Incorrect
Using None as default and creating a new object inside the function avoids sharing the same mutable object.
What will this code print?
def greet(name='Friend'):
print(f'Hello, {name}!')
greet()
greet('Alice')✗ Incorrect
The first call uses the default 'Friend', the second call uses the provided 'Alice'.
Explain what default arguments are and how they work in Python functions.
Think about function parameters that have a value ready if you don't give one.
You got /3 concepts.
Describe the problem with using mutable objects as default arguments and how to fix it.
Consider what happens if you change a list used as a default argument.
You got /3 concepts.