0
0
Pythonprogramming~5 mins

Polymorphism through functions in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is polymorphism in programming?
Polymorphism means one thing can take many forms. In programming, it allows functions or methods to work with different types of data or objects.
Click to reveal answer
beginner
How does polymorphism work with functions in Python?
In Python, polymorphism lets the same function name work with different types of inputs. The function behaves differently depending on the input type.
Click to reveal answer
beginner
Example: What will this code print?
def add(a, b):
    return a + b

print(add(2, 3))
print(add('Hi, ', 'there!'))
It prints:<br>5<br>Hi, there!<br>The same function add works for numbers and strings because + means addition for numbers and concatenation for strings.
Click to reveal answer
beginner
Why is polymorphism useful in programming?
It makes code simpler and flexible. You can use one function for many types of data, so you write less code and it works in more situations.
Click to reveal answer
intermediate
What happens if a function expects a certain type but gets another?
If the function can't handle the input type, Python will raise an error. Polymorphism works only if the function's operations make sense for the input types.
Click to reveal answer
What does polymorphism allow a function to do?
AChange its name automatically
BOnly work with numbers
CWork with different types of inputs
DRun faster
What will this code output?
def multiply(x, y):
    return x * y

print(multiply(3, 4))
print(multiply('Hi', 3))
A12 and HiHiHi
B7 and Hi3
CError and HiHiHi
D12 and Error
If a function uses + operator, which types can it work with in Python?
ANumbers and strings
BOnly numbers
COnly strings
DLists only
What error occurs if a function tries to add a number and a string?
ASyntaxError
BTypeError
CValueError
DNameError
Why is polymorphism called 'many forms'?
ABecause it changes the function name
BBecause it only works with classes
CBecause it runs multiple times
DBecause one function can behave differently with different inputs
Explain polymorphism through functions in your own words and give a simple example.
Think about how one function can add numbers and join strings.
You got /3 concepts.
    Describe why polymorphism is helpful when writing Python functions.
    Consider how one function can replace many similar functions.
    You got /4 concepts.