Junior — Middle
How can arguments with types be passed to functions?
sobes.tech AI
Answer from AI
In Python, type annotations are used to specify argument types. They do not affect code execution but assist with documentation and static analysis tools.
Example of a function with type annotations:
def greet(name: str, age: int) -> str:
return f"Hello, {name}! You are {age} years old."
print(greet("Anya", 25))
Here, name is expected to be a string (str), age an integer (int), and the function returns a string (str).
You can also use the typing module for more complex types, such as lists or dictionaries:
from typing import List
def process_items(items: List[int]) -> None:
for item in items:
print(item)
Annotations help improve code readability and maintainability, and they integrate with tools like mypy for static type checking.