Follow me to learn 🐍 Python in 5-minute a day fun quizzes! Find previous quiz here.
We're back with another fun and enlightening Python challenge! This time, we're delving into the world of type hints as guided by PEP 484. Are you ready to test your Python prowess?
We've got two Python functions, both aiming to do the same thing but written differently.
Which one follows the best practices as per PEP 484?
Sample 1
def greet(name):
return "Hello, " + name
print(greet(123))
Sample 2
def greet(name: str) -> str:
return f"Hello, {name}!"
print(greet("Alice"))
Post your answer in the comments – is it 0 for the first sample or 1 for the second? As usually, the correct answer with explanation will be in comment.
Top comments (1)
Correct answer
Sample 1 lacks type hints and allows any data type to be passed as an argument, which can lead to runtime errors. For example, passing an integer as in greet(123) would still work but doesn't align with the intended use of the function.
Sample 2 correctly uses type hints as per PEP 484. It specifies that the name parameter should be a string (str) and the return type of the function is also a string (str). This promotes code readability and helps in catching type-related errors during development.