Lesson 1 of 6 · Numbers, Strings and Operators · 2 min read · Updated
Numbers and arithmetic
Whole numbers, decimals, the seven arithmetic operators, and converting between types.
Python has two number types you will use every day: int for whole numbers and float for numbers with a decimal point. There is a third, complex, for engineering maths — you will rarely need it.
The arithmetic operators
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(7 ** 2)
9
5
14
3.5
3
1
49
/is true division and always gives a float.//is floor division: divide, then drop the fraction.%is the remainder.n % 2 == 0is the classic test for an even number.**is power:7 ** 2is 7 squared.
print(8 / 2)
print(round(3.14159, 2))
print(round(2.5), round(3.5))
print(0.1 + 0.2)
print(2 ** 100)
4.0
3.14
2 4
0.30000000000000004
1267650600228229401496703205376
Note
round(2.5) is 2, not 3. Python rounds a value exactly halfway to the nearest even number, which avoids a bias when you round many values. And 0.1 + 0.2 is not exactly 0.3 because computers store decimals in binary — round the result when you display money.
Python whole numbers have no size limit: 2 ** 100 is exact. Many languages would overflow long before that.
Converting between types
print(int(3.99))
print(int(-3.7))
print(int("42") + 1)
print(float("2.5") * 2)
print(str(100) + " percent")
3
-3
43
5.0
100 percent
Warning
int() cuts off the fraction — it does not round. int(3.99) is 3. And int("abc") or int("3.5") raises a ValueError: the text must look like a whole number.
What do 17 // 5 and 17 % 5 give?
Try this now
- Ask for a number of minutes and print it as hours and minutes using
//and%. - Print whether a number the user types is even or odd.
- Work out the simple interest on 50000 rupees at 7.5% for 3 years, rounded to 2 places.
Create a free account to save your progress, or sign in.