Junior — Middle
How is type annotation implemented and used in functions or variables in Python?
sobes.tech AI
Answer from AI
Type annotations in Python allow specifying expected types of function arguments and return values, as well as variable types. This helps improve code readability and enables static type checking tools (e.g., mypy) to detect errors.
Example of a function annotation:
def greet(name: str) -> str:
return f"Hello, {name}!"
Here, name should be a string, and the function returns a string.
For variables, annotations look like this:
age: int = 25
names: list[str] = ["Alice", "Bob"]
Annotations do not affect program execution; they serve for documentation and static analysis.