Challenge - 5 Problems
Default Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of function with mutable default argument
What is the output of this code when calling
append_number() three times in a row?Python
def append_number(num, lst=[]): lst.append(num) return lst print(append_number(1)) print(append_number(2)) print(append_number(3))
Attempts:
2 left
๐ก Hint
Think about how default arguments are evaluated once when the function is defined.
โ Incorrect
The default list lst is created once when the function is defined, not each time it is called. So all calls share the same list, accumulating the numbers.
โ Predict Output
intermediate1:30remaining
Output with default argument and keyword argument
What will this code print?
Python
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Alice")) print(greet("Bob", greeting="Hi"))
Attempts:
2 left
๐ก Hint
Check how the default argument is overridden by the keyword argument.
โ Incorrect
The first call uses the default greeting "Hello". The second call overrides it with "Hi".
โ Predict Output
advanced2:30remaining
Default argument evaluated once
What is the output of this code?
Python
def counter(start=0): def inner(): nonlocal start start += 1 return start return inner c1 = counter() c2 = counter(10) print(c1()) print(c1()) print(c2()) print(c2())
Attempts:
2 left
๐ก Hint
Each call to counter creates a new closure with its own start value.
โ Incorrect
Each counter() call returns a new function with its own start. Calling c1() increments from 0, c2() from 10.
๐ง Debug
advanced1:30remaining
Identify the error with default argument
What error does this code raise when called as
add_item(5)?Python
def add_item(item, items=None): items.append(item) return items add_item(5)
Attempts:
2 left
๐ก Hint
Check what happens when
items is None and you try to call append.โ Incorrect
The default items is None. Calling None.append() causes an AttributeError.
๐ Application
expert2:30remaining
Predict the dictionary content after function calls
Consider this function and calls. What is the content of
data after all calls?Python
def add_entry(key, value, data={}): data[key] = value return data data = add_entry('a', 1) data = add_entry('b', 2) data = add_entry('a', 3)
Attempts:
2 left
๐ก Hint
Remember that the default dictionary is shared across calls.
โ Incorrect
The default dictionary data is shared. The last call updates key 'a' to 3, so the dictionary has keys 'a' and 'b' with values 3 and 2.