Add Type Hints to a Function
Intermediate · Write the code · from Python Type Hints: Add Types, Generics, and the typing Module
From the lesson: How Do You Add Type Hints to Variables and Functions?
The syntax is simple. For variables, add a colon and the type after the name. For functions, annotate each parameter and use -> for the return type.
Read this part of the lessonAdd proper type hints to this function and its variables. The function takes a list of integers and returns their average as a float. Also add type hints to the two variables.
Make the function work correctly, then print the result for the list [10, 20, 30, 40].
# Add type hints to the function signature and variables
def average(numbers):
total = sum(numbers)
count = len(numbers)
return total / count
result = average([10, 20, 30, 40])
print(result)
More Type Hints exercises
- Type a Config FunctionIntermediate
- Predict the Output with Type HintsIntermediate
- Type a Higher-Order FunctionIntermediate
- Add Runtime Type CheckingIntermediate
- Type a Data Processing FunctionAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz