0
0
Pythonprogramming~20 mins

Default values in constructors in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Constructor Default Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of constructor with default values
What is the output of this Python code when creating an object without passing any arguments?
Python
class Car:
    def __init__(self, color='red', speed=0):
        self.color = color
        self.speed = speed

car = Car()
print(car.color, car.speed)
Ared 0
BNone 0
Cred None
DTypeError
Attempts:
2 left
💡 Hint
Look at the default values set in the constructor parameters.
Predict Output
intermediate
2:00remaining
Constructor default values with partial arguments
What will be printed when creating an object with one argument, leaving the other to default?
Python
class Book:
    def __init__(self, title='Unknown', pages=100):
        self.title = title
        self.pages = pages

book = Book('Python 101')
print(book.title, book.pages)
APython 101 100
BUnknown 100
CPython 101 Unknown
DTypeError
Attempts:
2 left
💡 Hint
Only the first parameter is given, the second uses its default.
Predict Output
advanced
2:00remaining
Effect of mutable default argument in constructor
What is the output of this code after creating two objects and modifying one object's list?
Python
class Basket:
    def __init__(self, items=[]):
        self.items = items

basket1 = Basket()
basket2 = Basket()
basket1.items.append('apple')
print(basket2.items)
A[]
BTypeError
CNone
D['apple']
Attempts:
2 left
💡 Hint
Think about what happens when a mutable default argument is shared.
Predict Output
advanced
2:00remaining
Correct way to avoid mutable default argument issue
What will be printed after creating two objects and modifying one object's list with this constructor?
Python
class Basket:
    def __init__(self, items=None):
        if items is None:
            items = []
        self.items = items

basket1 = Basket()
basket2 = Basket()
basket1.items.append('apple')
print(basket2.items)
A['apple']
BNone
C[]
DTypeError
Attempts:
2 left
💡 Hint
Check how the list is created inside the constructor.
🧠 Conceptual
expert
2:00remaining
Why avoid mutable default arguments in constructors?
Why is it recommended to avoid using mutable objects like lists or dictionaries as default values in constructor parameters?
ABecause mutable default arguments cause syntax errors in Python.
BBecause mutable default arguments are shared across all instances, causing unexpected behavior.
CBecause mutable default arguments cannot be modified inside the constructor.
DBecause mutable default arguments increase memory usage unnecessarily.
Attempts:
2 left
💡 Hint
Think about what happens when you change a mutable default argument in one object.