0
0
Pythonprogramming~10 mins

Default values in constructors in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to set a default value for the 'color' attribute in the constructor.

Python
class Car:
    def __init__(self, color=[1]):
        self.color = color

my_car = Car()
print(my_car.color)
Drag options to blanks, or click blank then click option'
ANone
B"red"
Cred
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around string default values.
Using a variable name without quotes as a default value.
2fill in blank
medium

Complete the constructor to give 'speed' a default value of 0.

Python
class Bike:
    def __init__(self, speed=[1]):
        self.speed = speed

my_bike = Bike()
print(my_bike.speed)
Drag options to blanks, or click blank then click option'
A0
B"0"
CNone
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string '0' instead of the number 0.
Leaving the default value empty.
3fill in blank
hard

Fix the error in the constructor by completing the default value for 'name'.

Python
class Person:
    def __init__(self, name=[1]):
        self.name = name

p = Person()
print(p.name)
Drag options to blanks, or click blank then click option'
ANone
B''
C0
D"Unknown"
Attempts:
3 left
💡 Hint
Common Mistakes
Using None without handling it in the code.
Using a number 0 as a name.
4fill in blank
hard

Fill both blanks to set default values for 'width' and 'height' in the constructor.

Python
class Rectangle:
    def __init__(self, width=[1], height=[2]):
        self.width = width
        self.height = height

rect = Rectangle()
print(rect.width, rect.height)
Drag options to blanks, or click blank then click option'
A1
B0
C"0"
D"1"
Attempts:
3 left
💡 Hint
Common Mistakes
Using strings instead of numbers for default sizes.
Setting default sizes to 0 which might represent no size.
5fill in blank
hard

Fill all three blanks to set default values for 'title', 'author', and 'pages' in the constructor.

Python
class Book:
    def __init__(self, title=[1], author=[2], pages=[3]):
        self.title = title
        self.author = author
        self.pages = pages

book = Book()
print(book.title, book.author, book.pages)
Drag options to blanks, or click blank then click option'
A"Untitled"
B"Anonymous"
C0
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Using None for strings without handling it.
Putting numbers in quotes.