← All lessons
Programming basics · Lesson 2 of 9

Numbers and maths

Python has two everyday kinds of number. Integers (int) are whole numbers like 7 or -3. Floats (float) have a decimal point, like 2.5. The kind of a value is called its type, and type(x) tells you what it is.

The operators are +, -, * (times) and / (divide). Dividing with / always gives a float, even when it comes out even: 10 / 2 is 5.0. Brackets work as in maths, and * and / happen before + and -.

print(10 / 2)
print(2 + 3 * 4)
print((2 + 3) * 4)
Prints
5.0
14
20

Three more come up all the time. // divides and drops the remainder (floor division), % gives just the remainder, and ** is "to the power of". % is handy for checking if a number is even: n % 2 is 0 for even numbers and 1 for odd ones.

print(17 // 5)
print(17 % 5)
print(2 ** 10)
Prints
3
2
1024

Text and numbers don't mix by themselves: "3" + 4 is an error, because Python won't guess whether you meant 7 or "34". Convert first. int("3") turns text into a whole number, float("2.5") into a decimal, and str(4) turns a number into text. + on two strings joins them.

print(int("3") + 4)
print("3" + str(4))
Prints
7
34

Practice

What does this print?

print(9 / 3)
More info

Quick reference

+ - * /Add, subtract, multiply, divide (/ gives a float).
//Floor division: 17 // 5 is 3.
%Remainder: 17 % 5 is 2. n % 2 == 0 means n is even.
**Power: 2 ** 3 is 8.
int() float() str()Convert a value to a whole number, a decimal or text.

The other computer science courses