Arithmetic
Python is a calculator:
7 + 2 # 9 add 7 - 2 # 5 subtract 7 * 2 # 14 multiply 7 / 2 # 3.5 divide (always a float) 7 // 2 # 3 floor divide: how many whole times 7 % 2 # 1 modulo: the remainder 7 ** 2 # 49 power
// and % are a team: // tells you "how many whole groups" and % tells you "what is left over".
See it run
cookies = 17 kids = 5 share = cookies // kids left = cookies % kids exact = cookies / kids
17 cookies, 5 kids. Three operators answer three different questions.
Practice arithmetic
Exercise 1
A movie runs minutes = 135. Make hours the whole hours (2) and leftover the remaining minutes (15) using // and %.
Exercise 2
29 pizza slices are shared between 4 friends. Everyone gets the same number of whole slices.
- each = slices per friend (7)
- spare = slices left in the box (1)
Calculate both from slices and people.
Exercise 3
A podcast is total_seconds = 7384 long. Split it into hours (2), minutes (3) and seconds (4), then print just the three numbers with print(hours, minutes, seconds), which shows 2 3 4.
There are 3600 seconds in an hour. Minutes are what is left after the hours, divided into 60s.
% and // have equal priority and run left to right, so total_seconds % 3600 // 60 means (total_seconds % 3600) // 60. Brackets make that easier to read.Free lesson: use the editor to practice it.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.