0
0
Pythonprogramming~10 mins

Duck typing concept 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 call the method that makes the object quack.

Python
class Duck:
    def quack(self):
        print("Quack!")

bird = Duck()
bird.[1]()
Drag options to blanks, or click blank then click option'
Aquack
Bwalk
Cswim
Dfly
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method that does not exist like 'fly' or 'swim'.
2fill in blank
medium

Complete the code to check if an object has a 'quack' method using duck typing.

Python
def make_it_quack(obj):
    if hasattr(obj, '[1]'):
        obj.quack()
    else:
        print("This object can't quack.")
Drag options to blanks, or click blank then click option'
Aquack
Bfly
Cswim
Dwalk
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for a wrong method name like 'fly' or 'swim'.
3fill in blank
hard

Fix the error in the code to correctly use duck typing to call 'quack' if available.

Python
class Dog:
    def bark(self):
        print("Woof!")

pet = Dog()
if hasattr(pet, '[1]'):
    pet.quack()
else:
    print("Pet can't quack.")
Drag options to blanks, or click blank then click option'
Awalk
Bquack
Crun
Dbark
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'bark' but calling 'quack' causes an error.
4fill in blank
hard

Fill both blanks to create a list of objects that can quack and call their quack method.

Python
class Duck:
    def quack(self):
        print("Quack!")

class Person:
    def quack(self):
        print("I'm pretending to be a duck!")

objects = [Duck(), Person(), 42]
for obj in objects:
    if hasattr(obj, '[1]'):
        obj.[2]()
Drag options to blanks, or click blank then click option'
Aquack
Bbark
Dfly
Attempts:
3 left
💡 Hint
Common Mistakes
Using different method names for check and call.
5fill in blank
hard

Fill all three blanks to create a function that calls 'quack' if available, else calls 'bark' if available, else prints a message.

Python
def make_sound(obj):
    if hasattr(obj, '[1]'):
        obj.[2]()
    elif hasattr(obj, '[3]'):
        obj.bark()
    else:
        print("No sound method found.")
Drag options to blanks, or click blank then click option'
Aquack
Cbark
Dfly
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing method names or calling wrong methods.