← All lessons
Python basics · Lesson 3 of 10

Numbers and maths

Python has two everyday kinds of number. Whole numbers like 7, 0 or -3 are called integers, int for short. Numbers with a decimal point, like 2.5 or 10.0, are called floats (because the decimal point can "float" to any position). The kind of a value is called its type.

The maths symbols are called operators: + add, - subtract, * multiply (a star, because there's no × key) and / divide. Dividing with / always gives a float, even when it comes out even.

print(7 + 3)
print(7 - 10)
print(6 * 7)
print(10 / 4)
print(10 / 2)
Prints
10
-3
42
2.5
5.0

Python follows the usual maths order: brackets first, then powers, then * and /, then + and -. When in doubt, add brackets; they make your meaning clear to people too.

print(2 + 3 * 4)
print((2 + 3) * 4)
Prints
14
20

Three more operators come up all the time. // divides and throws away the remainder (it's called floor division). % gives just the remainder (it's called modulo). ** means "to the power of": 2 ** 3 is 2 × 2 × 2.

print(17 // 5)
print(17 % 5)
print(2 ** 3)
Prints
3
2
8

% is surprisingly handy: a number is even when n % 2 is 0, and minutes % 60 gives the minutes left over after the whole hours.

Floats are stored in binary, so some decimals can't be stored exactly, and tiny errors show up: 0.1 + 0.2 prints 0.30000000000000004. This happens in every language. Use round(x, 2) to round to 2 decimal places when you show a result. round() with no second number rounds to a whole number.

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(round(3.7))
Prints
0.30000000000000004
0.3
4

Variables work with numbers as you'd expect, and there are shortcuts for changing one: x += 5 means x = x + 5, and -=, *= and /= work the same way.

price = 8
price *= 3
price -= 4
print(price)
Prints
20

Practice

What does this print?

print(12 / 4)
More info

Quick reference

int / floatA whole number / a number with a decimal point.
+ - * /Add, subtract, multiply, divide. / always gives a float.
// and %Whole-number division and the remainder: 17 // 5 is 3, 17 % 5 is 2.
**Power: 2 ** 3 is 8.
round(x, 2)x rounded to 2 decimal places. round(x) rounds to a whole number.
x += 1Shortcut for x = x + 1. Also -=, *=, /=.

Related courses