Foundations · Lesson 2 of 18 · 16 min
Types and operators
Numbers, booleans, and the way Python computes.
- Use int, float, and bool precisely
- Predict floor division and modulo
- Know when to use //, /, and **
Integers have no size limit
A Python `int` is arbitrary-precision. Factorials, cryptography, and big counters just work — they get slower and use more memory, but they do not overflow. That is different from C, Java, and JavaScript's Number.
`bool` is a subclass of `int`. `True` is 1 and `False` is 0. You can add them, which is occasionally useful and occasionally a smell: `sum(flags)` counts True values because of this.
print(True + True)
print(isinstance(True, int))
print(10 ** 50)
print(type(1 / 2), 1 / 2)
print(type(1 // 2), 1 // 2)
print(7 % 3, -7 % 3)
print(7 // 3, -7 // 3)Operators that look like math
`**` binds tighter than unary minus in a way that surprises people: `-2 ** 2` is `-4`, because it parses as `-(2 ** 2)`. Use `(-2) ** 2` when you mean the square of negative two.
Comparisons chain: `1 < x < 10` is `1 < x and x < 10`, and `x` is evaluated once. This is real syntax, not a trick.
For floats, equality is a trap. `0.1 + 0.2 == 0.3` is False because binary floating point cannot represent those decimals exactly. Compare with a tolerance, or use `decimal.Decimal` / `fractions.Fraction` when exactness matters.
x = 5
print(1 < x < 10)
print(-2 ** 2, (-2) ** 2)
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 10) == round(0.3, 10))Numeric types you will actually use
| Type | Example | Notes |
|---|---|---|
| int | 42, 0b101, 0xFF | Arbitrary precision |
| float | 3.14, 1e-6 | IEEE-754 binary64 |
| complex | 2+3j | Real and imag are floats |
| bool | True, False | Subclass of int |
Check yourself
Quiz
1.What is `5 / 2` in Python 3?
2.What is `-7 // 3`?
3.Why can `True + 4` equal 5?
Practice
Exercise
Write `floor_percent(n, d)` that returns how many whole percent n is of d, using integer floor division. For example 2 of 5 is 40. If d is 0, return 0.
Tutor
Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.