Junior — Middle
Can you give examples of using type annotations in code?
sobes.tech AI
Answer from AI
Type annotations in Python are used to specify the expected types of variables, function arguments, and return values. This helps improve code readability and allows static analysis tools (e.g., mypy) to find errors.
Examples:
from typing import List, Optional
def greet(name: str) -> str:
return f"Hello, {name}!"
def sum_numbers(numbers: List[int]) -> int:
return sum(numbers)
def find_user(user_id: int) -> Optional[str]:
users = {1: "Alice", 2: "Bob"}
return users.get(user_id)
# Usage
print(greet("John"))
print(sum_numbers([1, 2, 3]))
print(find_user(3)) # None if user not found
Here:
name: str— the function argument should be a string.-> str— the function returns a string.List[int]— a list of integers.Optional[str]— the return value can be a string or None.
Type annotations do not affect code execution but help developers and analysis tools.