CodeBlanks Logo Icon CodeBlanks

Type hints basics

Learn type hints like int, str, list.

Type hints basics

A type hint marks the expected type of a parameter and return value:

def add(a: int, b: int) -> int:
    return a + b

Python does not enforce type hints at runtime; they are only for documentation and static analysis (mypy, pyright). Passing the wrong type still runs.

Type hints are very useful in large projects; they catch wrong usage early.

Common type hints

Common type hints are int, float, str, bool, list, dict. More complex types are written as list[int], dict[str, int]:

def count_words(words: list[str]) -> int:
    return len(words)

This clearly marks that the function expects a list[int] and returns int. IDEs use this info to give hints.

Practice Write a function with a type hint

Define a function called square with parameter n: int and return type -> int. The body does return n * n. Assign square(5) to result. Then print print(result).

Starter code

main.py
# Define the square function

Sample solution

main.py
def square(n: int) -> int:
    return n * n
result = square(5)
print(result)

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the type hint

Question
def add(a: ____, b: int) -> int:
    return a + b
Answer
def add(a: int, b: int) -> int:
    return a + b

Explanation: a: int marks the parameter type.

2 What does a type hint do at runtime?

  • Slows the code down
  • Raises an error on wrong type
  • Does nothing; it is for documentation Correct answer
  • Compiles the code

Explanation: A type hint does not affect runtime; it is only for documentation and static analysis.

3 Match the type hints

Term Meaning
int Integer
str String
list[int] List of integers
-> int Returns int

All lessons in Beginner