Bird
Raised Fist0
Pythonprogramming~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of using default values in a Python class constructor (__init__ method)?
easy
A. To prevent the class from being instantiated
B. To make the constructor run faster
C. To allow creating objects without providing all arguments
D. To force the user to always provide all arguments

Solution

  1. Step 1: Understand default values in constructors

    Default values let you set a value for a parameter if no argument is given when creating an object.
  2. Step 2: Identify the effect on object creation

    This means you can create an object without giving all arguments, and the defaults fill in the missing ones.
  3. Final Answer:

    To allow creating objects without providing all arguments -> Option C
  4. Quick Check:

    Default values = optional arguments [OK]
Hint: Defaults let you skip arguments when creating objects [OK]
Common Mistakes:
  • Thinking defaults speed up the constructor
  • Believing defaults prevent object creation
  • Assuming defaults force all arguments
2. Which of the following is the correct way to set a default value for the parameter age in a Python class constructor?
easy
A. def __init__(self, age:30):
B. def __init__(self, age): age=30
C. def __init__(self, age): age == 30
D. def __init__(self, age=30):

Solution

  1. Step 1: Recall Python syntax for default parameters

    Default values are set by assigning a value in the parameter list, like age=30.
  2. Step 2: Check each option

    def __init__(self, age=30): uses correct syntax. def __init__(self, age): age=30 tries to assign inside the method header, which is invalid. def __init__(self, age): age == 30 uses comparison operator instead of assignment. def __init__(self, age:30): uses incorrect type hint syntax.
  3. Final Answer:

    def __init__(self, age=30): -> Option D
  4. Quick Check:

    Default parameter = param=value [OK]
Hint: Default values go in the parameter list with = [OK]
Common Mistakes:
  • Assigning default inside the method body
  • Using == instead of = for defaults
  • Confusing type hints with default values
3. What will be the output of this code?
class Person:
    def __init__(self, name, age=25):
        self.name = name
        self.age = age

p = Person('Alice')
print(p.name, p.age)
medium
A. Alice 25
B. Alice None
C. Alice 0
D. Error: missing argument for age

Solution

  1. Step 1: Analyze the constructor parameters

    The constructor has age=25 as a default, so if age is not given, it uses 25.
  2. Step 2: Check object creation and print

    We create p = Person('Alice') without age, so age is 25. Printing p.name and p.age shows 'Alice 25'.
  3. Final Answer:

    Alice 25 -> Option A
  4. Quick Check:

    Missing argument uses default [OK]
Hint: Missing argument uses default value [OK]
Common Mistakes:
  • Expecting error when argument is missing
  • Assuming default is None if not given
  • Confusing default with zero or empty string
4. Find the error in this class constructor:
class Car:
    def __init__(self, model='Sedan', year):
        self.model = model
        self.year = year
medium
A. Missing return statement in __init__
B. Default parameter must come after non-default parameters
C. self is missing in parameters
D. Cannot assign to self attributes in constructor

Solution

  1. Step 1: Check parameter order in constructor

    In Python, parameters with default values must come after parameters without defaults.
  2. Step 2: Identify the error in parameter order

    Here, model='Sedan' is a default parameter before year which has no default. This causes a syntax error.
  3. Final Answer:

    Default parameter must come after non-default parameters -> Option B
  4. Quick Check:

    Default params last in list [OK]
Hint: Put all default parameters after non-default ones [OK]
Common Mistakes:
  • Placing default parameters before required ones
  • Thinking __init__ needs return
  • Forgetting self parameter
5. You want to create a class Book where the author defaults to 'Unknown' and pages defaults to 100 if not provided. Which constructor is correct?
hard
A. def __init__(self, author='Unknown', pages=100): self.author = author; self.pages = pages
B. def __init__(self, author, pages=100='Unknown'):
C. def __init__(self, author='Unknown', pages):
D. def __init__(self, author='Unknown', pages=100):

Solution

  1. Step 1: Check parameter defaults and order

    Both author and pages have default values, so order is flexible. Options B and C have syntax errors.
  2. Step 2: Verify constructor body assigns attributes

    def __init__(self, author='Unknown', pages=100): self.author = author; self.pages = pages correctly sets defaults and assigns self.author and self.pages inside the constructor body.
  3. Final Answer:

    def __init__(self, author='Unknown', pages=100): self.author = author; self.pages = pages -> Option A
  4. Quick Check:

    Defaults set in params, assign inside method [OK]
Hint: Set defaults in params, assign inside __init__ [OK]
Common Mistakes:
  • Incorrect default assignment syntax
  • Not assigning parameters to self
  • Mixing default values and assignments