Numbers and arithmetic

Python has two everyday kinds of number: int (whole numbers like 7 or -3) and float (numbers with a decimal point like 2.5).

The operators:

  • + - * do what you expect.
  • / is normal division and always gives a float: 6 / 2 is 3.0, not 3.
  • // is floor division: divide, then round down. 7 // 2 is 3.
  • % is the remainder (often called modulo): 7 % 2 is 1. Super handy: n % 2 == 0 means n is even.
  • ** is power: 2 ** 10 is 1024.

Python follows the usual order: ** first, then * / // %, then + -. Use brackets when in doubt, so (2 + 3) * 4 is 20.

Careful with negatives: // rounds down, towards minus infinity, so -7 // 2 is -4, not -3.

Now the famous surprise:

print(0.1 + 0.2)   # 0.30000000000000004

Python is not broken. Computers store floats in binary, and 0.1 has no exact binary form, the same way 1/3 has no exact decimal form (0.3333...). The tiny error shows up when you print. Two lessons from this: never test floats with == when exactness matters, and use round(x, 2) when you want a tidy result.

Ints, on the other hand, are exact and have no size limit. 2 ** 100 gives you all 31 digits, no problem.

Try it yourself

Edit it. Break it. Run it again.
print(7 / 2)     # 3.5   normal division, always a float
print(7 // 2)    # 3     floor division
print(7 % 2)     # 1     remainder
print(2 ** 10)   # 1024  power
print(-7 // 2)   # -4    rounds down, not towards zero

print(0.1 + 0.2)              # the classic float surprise
print(round(0.1 + 0.2, 2))    # tidy it up
print(2 ** 100)               # ints never overflow
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Minutes and seconds

total is a number of seconds. Use // and % to work out the whole minutes and the leftover seconds, and print them so the output is exactly 200 seconds is 3 min 20 s. Your code should work for any value of total, so do not type 3 or 20 yourself.

total = 200
minutes = 0
seconds = 0
print(total, "seconds is", minutes, "min", seconds, "s")
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Pizza maths

Eight friends share slices = 30 slices. Print how many whole slices each person gets, then on the next line how many slices are left over. The output should be 3 on the first line and 6 on the second.

slices = 30
people = 8
print(slices / people)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.