01Annotate a function
main.py
def greet(name: str) -> str:
return "Hello, " + name
print(greet("World"))Output
Hello, World
Python type hints with runnable examples: parameters, return types, variables, Optional, multiple return values, *args and **kwargs, and generators.
def greet(name: str) -> str:
return "Hello, " + name
print(greet("World"))Hello, World
age: int = 25
height: float = 1.75
name: str = "Ada"
print(age, height, name)25 1.75 Ada
from typing import List
def total(nums: List[int]) -> int:
return sum(nums)
print(total([1, 2, 3, 4]))10
from typing import Optional
def find(x: int) -> Optional[str]:
if x > 0:
return "positive"
return None
print(find(5))
print(find(-1))positive None
def min_max(numbers: list[int]) -> tuple[int, int]:
return min(numbers), max(numbers)
low, high = min_max([4, 9, 1, 7])
print(low, high)1 9
# *tags: str means every extra positional argument is a str.
# **scores: int means every keyword argument's value is an int.
def describe(*tags: str, **scores: int) -> str:
total = sum(scores.values())
return f"{', '.join(tags)}: {total} points"
print(describe("math", "quiz", alice=8, bob=7))math, quiz: 15 points
from collections.abc import Iterator
def countdown(n: int) -> Iterator[int]:
while n > 0:
yield n
n -= 1
print(list(countdown(3)))[3, 2, 1]