Numbers & operators
int and float, arithmetic and division gotchas, precedence, comparisons, math and Decimal for money.
Numbers are everywhere: prices, scores, sensor readings, pixel coordinates. Python has two everyday numeric types — int and float — plus a rich set of operators and a few precise tools for when "close enough" isn't good enough.
Integers and floats#
Unlike Java or C, Python's int grows as large as memory allows, so you never need to worry about overflow with whole numbers.
Mixing types is fine: an int combined with a float gives a float.
Arithmetic operators#
The two division operators are the classic gotcha:
% is handy for "every Nth item" and "is it even?" checks:
Operator precedence#
Python follows the usual maths rules: ** first, then * / // %, then + -. Use parentheses to make intent obvious:
Augmented assignment#
Updating a variable based on its current value is so common that there's a shortcut for every operator:
Python has no ++ or --; write count += 1.
Comparison and boolean operators#
Comparisons produce True or False, and can be chained just like in maths:
and and or short-circuit: and stops at the first falsy value, or stops at the first truthy one. They also return one of their operands, which enables a common default-value idiom:
Useful built-in functions and the math module#
Watch out: round() uses banker's rounding for exact halves — it rounds to the nearest even number. So round(2.5) is 2 and round(3.5) is 4.
The floating-point trap#
Floats are stored in binary, which can't represent most decimal fractions exactly. The result is tiny rounding errors:
This isn't a Python bug — every language using IEEE 754 floats behaves this way. Two fixes:
Create Decimal values from strings, not floats — Decimal(0.1) faithfully copies the float's tiny error. Many financial apps simply store amounts as integer paise or cents instead.
Formatting numbers for humans#
You'll learn f-strings fully in the next lesson, but here's a taste of number formatting:
A worked example: splitting a bill#
Common mistakes#
- Expecting
/to give an int.10 / 2is5.0. Use//when you need a whole number. - Comparing floats with
==. Usemath.isclose(). - Forgetting that
input()returns text."5" * 2is"55", not10— convert withint()first. - Using floats for money. Use
Decimalor integer paise/cents.
What's next#
Numbers covered — now for text. Next lesson: strings and f-strings, the tools you'll use to build every message your program shows.
Check your understanding
Quick quiz
1.What does
7 // 2evaluate to in Python?2.Why does
0.1 + 0.2 == 0.3evaluate toFalse?3.What is the value of
2 ** 3 ** 2?
Finished reading?
Mark this lesson complete to track your progress.