Reference · module 6
Numbers that behave
Everything this module explains, on one page.
int and float
Tell whole numbers from fractional ones.
- 3 is an int, 3.0 is a float. The dot is the whole difference, and it changes what comes out of arithmetic.
- Plain division always returns a float, even when it divides evenly: 6 / 3 is 2.0, not 2.
- Mix an int and a float and the result is a float. Python widens rather than rounds.
The mistake you are about to make
int(2.7) → 3
int(2.7) → 2
int() looks like rounding to a whole number. It simply drops the fractional part, however large it is. Rounding is round().
// and %
Divide into whole parts and a remainder.
- // divides and throws the fraction away: 7 // 2 is 3. It is called floor division because it rounds down.
- % gives what is left over: 7 % 2 is 1. Together they answer «how many whole ones, and how much remains».
- n % 2 == 0 is the ordinary test for even. Any divisor works: n % 5 == 0 asks about fives.
The mistake you are about to make
-7 // 2 → -3
-7 // 2 → -4
It is called integer division, so it looks like it drops the fraction. It rounds down, which for negative numbers means away from zero, not towards it.
Rounding
Round without surprises.
- round(x) gives the nearest whole number, and round(x, 2) keeps two decimals.
- Floats are stored approximately, so 0.1 + 0.2 is not exactly 0.3. This is not a Python bug; it is how binary fractions work.
- So never compare floats with ==. Compare the rounded values, or check the difference is tiny.
The mistake you are about to make
0.1 + 0.2 == 0.3
round(0.1 + 0.2, 2) == 0.3
The check looks obvious and comes back False. Floats are stored approximately — a property of binary fractions, not a Python bug. Compare rounded values.
Counting up
Update a number in place.
- total += 1 means total = total + 1. The same shortcut exists for -=, *= and /=.
- A counter has to start somewhere, and that is almost always zero, set before the loop rather than inside it.
- Set it inside the loop and it resets on every pass, so the answer is whatever the last item was.
The mistake you are about to make
total = 0 inside the loop
total = 0 before the loop
The zero looks like part of the counting, so it drifts inside with the rest. The counter then resets every pass and the answer is just the last item.
A bit of maths
Use the built-in number tools.
- abs() drops the sign, min() and max() pick the smallest and largest. All three are built in, no import needed.
- sum(numbers) adds a whole list in one call, which is shorter and clearer than a loop with a counter.
- ** raises to a power: 2 ** 10 is 1024. It binds tighter than multiplication.
The mistake you are about to make
sum = 0
total = 0
Sum is the obvious name for a total. It is also the name of a built-in function: assign zero to it and you lose the function for the rest of the program.