Add Runtime Type Checking
Intermediate · Write the code · from Python Type Hints: Add Types, Generics, and the typing Module
From the lesson: What Is the Difference Between Runtime and Static Type Checking?
This is the most important thing to understand about Python type hints: they exist in two separate worlds.
Read this part of the lessonWrite a function safe_divide(a: float, b: float) -> str that:
1. Checks that both arguments are int or float using isinstance. If not, return 'Error: arguments must be numbers'.
2. Checks if b is zero. If so, return 'Error: division by zero'.
3. Otherwise, returns the result as a string with 2 decimal places.
print(safe_divide(10, 3)) # 3.33
print(safe_divide(10, 0)) # Error: division by zero
print(safe_divide("10", 3)) # Error: arguments must be numbersdef safe_divide(a: float, b: float) -> str:
# Add runtime type checking
pass
print(safe_divide(10, 3))
print(safe_divide(10, 0))
print(safe_divide('10', 3))
More Type Hints exercises
- Add Type Hints to a FunctionIntermediate
- Type a Config FunctionIntermediate
- Predict the Output with Type HintsIntermediate
- Type a Higher-Order FunctionIntermediate
- Type a Data Processing FunctionAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz