Chuyển đến nội dung chính
eLearner.app
Mô-đun 9 · Bài học 1 trong tổng số 433/36 trong khóa học~12 min
Bài học theo mô-đun (1/4)

Gợi ý gõ: các loại chú thích

Type hints (type annotations) are optional declarations that say "this variable/parameter has type X". Python does NOT verify them at runtime: they are for you, your editor (autocomplete!) and tools like mypy or pyright that perform static type-checking.

Annotating variables

Python
nome: str = "Ada"
anni: int = 36
attivo: bool = True
prezzi: list[float] = [1.2, 3.4]

The syntax is name: type = value. Without a value it is a pure declaration:

Python
risultato: int  # nessuna assegnazione, solo "annuncio del tipo"

Annotating functions

Python
def saluta(nome: str, urlante: bool = False) -> str:
    s = f"Ciao {nome}"
    return s.upper() if urlante else s

def somma(numeri: list[int]) -> int:
    return sum(numeri)

Syntax: param: type for each parameter, -> type for the return. A function that returns nothing uses -> None.

Built-in generic types (Python 3.9+)

Python
nomi: list[str] = ["a", "b"]
mappa: dict[str, int] = {"x": 1}
coppia: tuple[int, str] = (1, "ok")
unici: set[int] = {1, 2, 3}

Optional and Union

A value that may be None:

Python
def trova_utente(id: int) -> str | None:
    if id == 1:
        return "Ada"
    return None

X | None is the modern syntax (Python 3.10+). Equivalent: Optional[X] from typing. For unions of multiple types: int | str | float.

typing: useful tools

Python
from typing import Any, Callable

def applica(f: Callable[[int], int], x: int) -> int:
    return f(x)

valore: Any = "qualunque cosa"  # disabilita il check
  • Any = "don't check" (use sparingly).
  • Callable[[arg1, arg2], return] = a function that takes those parameters and returns that type.

mypy: the type-checker

You install mypy, run mypy file.py, and it tells you whether the types line up:

Bash
$ mypy script.py
script.py:5: error: Argument 1 to "somma" has incompatible type "str"; expected "int"

Checking types with mypy

Python's type hints are not enforced at runtime by the interpreter; they are ignored during execution. To validate type correctness, you must run an external static analysis tool like mypy by executing the command mypy script.py in your terminal.

Try it yourself

tập thể dục#python.m9.l1.e1
Nỗ lực: 0Đang tải…

Define a function `double(numbers: list[int]) -> list[int]` that returns a list with each element multiplied by 2. Call it with [1, 2, 3] and assign to `r`. Evaluate `r`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use a list comprehension or a for loop.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#python.m9.l1.e2
Nỗ lực: 0Đang tải…

Define `first_or_none(items: list[int]) -> int | None` that returns the first element if the list is non-empty, otherwise None. Assign `a = first_or_none([10, 20])` and `b = first_or_none([])`. Evaluate `(a, b)`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

`if items` is true when the list is NOT empty.

Giải pháp khả dụng sau 3 lần thử

Additional challenge

tập thể dục#python.m9.l1.e3
Nỗ lực: 0Đang tải…

Write a function `double_value(n: int) -> int` that takes an integer, multiplies it by 2, and returns the result. Make sure to specify type hints for both the parameter and the return value. Finally, evaluate `double_value(5)`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use n: int as the parameter and -> int after the function signature.

Giải pháp khả dụng sau 3 lần thử