AnyCompiler

Numbers and Basic Math Operators

Python has two number types you'll use constantly: int for whole numbers, float for anything with a decimal point. Most of the arithmetic operators work exactly like a calculator, but two of them are Python-specific and worth knowing before you hit them by accident.

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Output
13
7
30
3.3333333333333335
3
1
1000
  • + - * work exactly like you'd expect
  • / is division, and it always returns a float, even if the result is a whole number
  • // is floor division — divides, then rounds down to the nearest whole number
  • % is the modulo operator — gives you the remainder after division
  • ** is exponentiation — a ** b means a to the power of b

/ vs // — the one that trips people up

Regular division (/) always gives you a float back, even when both numbers are whole. Floor division (//) divides and then drops anything after the decimal point — it doesn't round to the nearest whole number, it always rounds down.

print(5 / 2)
print(5 // 2)
print(5.0 // 2)
Output
2.5
2
2.0

Notice the last line: floor division on a float still returns a float (2.0, not 2) — Python keeps the type consistent with what you gave it. Mixing an int and a float in any operation always produces a float.

Rounding

round() rounds a number to however many decimal places you specify — or to the nearest whole number if you leave that argument out.

pi = 3.14159
print(round(pi, 2))
print(round(pi))
Output
3.14
3

Next: strings — how text actually works in Python, and the methods you'll reach for constantly.

Practice exercise

Given a = 17 and b = 5, print the result of a // b, then print the result of a % b.