0
0
Pythonprogramming~5 mins

Default arguments in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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:
['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?
Adef func(x): default=10
Bdef func(x): x=10
Cdef func(x=10):
Ddef func(x:10):
If a function has a default argument, what happens when you call it without that argument?
AThe argument becomes None.
BThe default value is used.
CAn error occurs.
DThe function ignores the parameter.
Why can using a mutable object like a list as a default argument cause problems?
ABecause it creates a new object every call.
BBecause Python does not allow lists as defaults.
CBecause mutable objects cannot be default arguments.
DBecause the same object is shared across calls.
How can you avoid issues with mutable default arguments?
AUse None as the default and create a new object inside the function.
BUse an empty list as default anyway.
CAvoid default arguments altogether.
DUse global variables instead.
What will this code print?
def greet(name='Friend'):
    print(f'Hello, {name}!')

greet()
greet('Alice')
AHello, Friend!<br>Hello, Alice!
BHello, !<br>Hello, Alice!
CHello, Friend!<br>Hello, Friend!
DError
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.