Numbers and Operators
Division splits into three different operators in Python. Get to know them and the surprises they hide.
The three divisions
/ true division, // floor division, % the remainder.
Mixing ints and floats
An operation involving a float answers in floats. Watch the types change as you edit.
The operator set
2 ** 10 is 2 raised to the 10th-7 // 2 is -4, not -3. Floor division always rounds down, toward minus infinity, not toward zero.Numbers and Operators: A Practical Guide
Python 3 split division into two on purpose — each half is what a different kind of code actually wants.
Quick Context
Older languages gave you one division that returned a whole number, quietly throwing away the fraction. Python 3 decided that was a silent bug factory: true division / keeps the fraction and answers in float; floor division // is the "whole-number division" people were actually reaching for — useful for splitting a list into equal chunks, or turning seconds into minutes.
What modulo is for
% returns the remainder after floor division: 7 % 3 is 1 because 7 is 2 threes and 1 left over. It is the operator behind the two most common checks in data work: n % 2 == 0 tests whether a number is even, and index % length wraps an index around a list, which is exactly how carousels and round-robins keep from falling off the end.
Interactive Exploration Guide
- Read the first four lines. Line by line: 3.5, then 3 (fraction thrown away), then 1 (the leftover), then 1024. Note that
7 // 2gives 3 while7 / 2gives 3.5 — same inputs, different promises. - Check the types. In the second editor,
4 + 2.0returns6.0, a float, because one operand was a float. Every operator follows this rule: the float wins. - Break on zero. Add
print(1 / 0)to either editor and run.ZeroDivisionErroris Python telling you the operation is undefined — the message names the exact line that caused it. - Explore modulo yourself. Replace the numbers with a few of your own, one pair at a time, and check the pattern:
x % yis always between0andy - 1. That boundedness is why it is so useful for wrapping.
Key Takeaway
Python has three division-shaped operators for three different jobs: / when you want the exact answer, // when you want whole-number chunks, and % when you want the remainder that chunking throws away. Getting the right one wrong is a classic source of bugs that produce no error at all — the program just silently rounds. When numbers misbehave, check your operators before your logic.