0
0
Pythonprogramming~20 mins

Default arguments in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Default Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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))
A
[1]
[2]
[3]
BTypeError
C
[1]
[1]
[1]
D
[1]
[1, 2]
[1, 2, 3]
Attempts:
2 left
๐Ÿ’ก Hint
Think about how default arguments are evaluated once when the function is defined.
โ“ Predict Output
intermediate
1: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"))
AHello, Alice!\nHi, Bob!
BHello, Alice!\nHello, Bob!
CHi, Alice!\nHi, Bob!
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Check how the default argument is overridden by the keyword argument.
โ“ Predict Output
advanced
2: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())
A
0
1
10
11
B
1
1
11
11
C
1
2
11
12
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Each call to counter creates a new closure with its own start value.
๐Ÿ”ง Debug
advanced
1: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)
AAttributeError
BTypeError
CNameError
DNo error, returns [5]
Attempts:
2 left
๐Ÿ’ก Hint
Check what happens when items is None and you try to call append.
๐Ÿš€ Application
expert
2: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)
A{'a': 1, 'b': 2, 'a': 3}
B{'a': 3, 'b': 2}
C{'a': 1, 'b': 2}
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Remember that the default dictionary is shared across calls.