Basic hints
- Python course
- Advanced
- Lesson 7/83
- 5 min
Learn basic type hints like int, str, list.
Basic hints
Type hints add type information to variables, parameters and return values. Python does not enforce them; tools (mypy, IDEs) check them.
Basic types: int, str, float, bool. You write count: int = 0 for a variable; for a function you write def add(a: int, b: int) -> int:.
def add(a: int, b: int) -> int:
return a + b
name: str = "Ayşe"
count: int = 0The arrow -> marks the return type. Hints do not change runtime behavior; they improve readability and tooling.
Reading hinted functions
A hinted function signature tells you what type it expects and what it returns. This helps when reading code and using IDE completion.
Example: def greet(name: str) -> str: takes a string and returns a string. def is_even(n: int) -> bool: takes an integer and returns true or false.
If you pass the wrong type, Python still runs; a hint is only a declaration. But tools like mypy catch the error.
Practice Write a hinted add function
Define a function add(a: int, b: int) -> int. The body contains return a + b. Call print(add(3, 4)).
Starter code
# add function: takes two ints, returns int
# sum the two parameters and return
# print the result of add(3, 4)Sample solution
def add(a: int, b: int) -> int:
return a + b
print(add(3, 4))Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When are type hints enforced by Python?
- Only during import
- On every function call
- Never at runtime; only tools check them Correct answer
- Only when an error occurs
Explanation: Hints are inert at runtime; mypy or an IDE checks them.
2 Add the return type
def add(a: int, b: int) ____ int:
return a + b
def add(a: int, b: int) -> int:
return a + b
Explanation: -> marks the return type; -> int says an integer is returned.
3 Match the type and meaning
| Term | Meaning |
|---|---|
int |
Integer |
str |
String |
float |
Decimal number |
bool |
True/false |