0
0
Pythonprogramming~20 mins

Duck typing concept in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Duck Typing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this duck typing example?
Consider the following Python code using duck typing. What will it print?
Python
class Bird:
    def fly(self):
        return "Flying in the sky"

class Airplane:
    def fly(self):
        return "Flying through clouds"

def lets_fly(thing):
    return thing.fly()

print(lets_fly(Bird()))
A"Flying in the sky"
BTypeError
CAttributeError
D"Flying through clouds"
Attempts:
2 left
💡 Hint
Look at which class instance is passed to lets_fly function.
Predict Output
intermediate
2:00remaining
What happens when an object lacks the expected method?
What will be the output of this code?
Python
class Fish:
    def swim(self):
        return "Swimming in water"

def lets_fly(thing):
    return thing.fly()

print(lets_fly(Fish()))
A"Swimming in water"
BAttributeError
C"Flying in the sky"
DTypeError
Attempts:
2 left
💡 Hint
Check if Fish has a fly method.
🧠 Conceptual
advanced
1:30remaining
Which statement best describes duck typing?
Choose the best description of duck typing in Python.
ARestricting objects to a specific class hierarchy.
BChecking an object's type before using it.
CUsing an object's methods and properties without checking its type.
DUsing static type annotations to enforce types.
Attempts:
2 left
💡 Hint
Think about how Python treats objects based on their behavior, not their type.
Predict Output
advanced
2:00remaining
What is the output of this duck typing with multiple objects?
What will this code print?
Python
class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

def animal_sound(animal):
    return animal.speak()

print(animal_sound(Dog()))
print(animal_sound(Cat()))
A"Woof!\nMeow!"
B"Meow!\nWoof!"
CAttributeError
DTypeError
Attempts:
2 left
💡 Hint
Check the order of print statements and which class instances are passed.
🔧 Debug
expert
2:30remaining
Why does this duck typing code raise an error?
This code is intended to use duck typing but raises an error. What is the cause?
Python
class Car:
    def drive(self):
        return "Driving fast"

def lets_drive(vehicle):
    return vehicle.drive()

print(lets_drive("fast car"))
ANo error, prints "Driving fast"
BTypeError because string has no drive method
CSyntaxError due to missing colon
DAttributeError because string has no drive method
Attempts:
2 left
💡 Hint
Check if the string "fast car" has a drive method.