Python Numbers
Python has two main kinds of numbers. An int is a whole number, positive or negative, with no fixed limit on its size. A float is a number with a decimal point, such as 2.5 or 0.1. Python also has complex numbers for engineering and science, written with a j, like 3 + 4j.
Arithmetic
The usual operators work as you expect, and a few are worth learning carefully:
a, b = 17, 5
print(a + b, a - b, a * b)
print(a / b) # true division: always a float
print(a // b) # integer division: rounds down
print(a % b) # remainder (modulo)
print(a ** 2) # power
print(-17 // 5, -17 % 5)22 12 85 3.4 3 2 289 -4 3
/ always gives a float, even for 10 / 2, which is 5.0. // divides and rounds down to a whole number, which is why -17 // 5 is -4, not -3. The remainder % is useful for checking whether a number is even (n % 2 == 0) or for taking the last digit (n % 10).
Mixing int and float
When an int and a float meet in a calculation, the result is a float. Floats are stored in binary, so some decimal fractions cannot be stored exactly, and tiny rounding differences can appear:
print(2 + 3.0)
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(round(3.14159, 3), round(7.5), round(8.5))5.0 0.30000000000000004 0.3 3.142 8 8
round rounds to a number of decimals. With no decimals it rounds to the nearest even number when a value is exactly halfway, which is why both 7.5 and 8.5 become 8. For money, either round when you print, or use the decimal module.
Big whole numbers
Python integers grow as large as needed, so you never get an overflow with whole numbers:
print(2 ** 100)
print(1_000_000 * 1_000_000)
print(abs(-12), max(3, 9, 4), min(3, 9, 4))1267650600228229401496703205376 1000000000000 12 9 3
Underscores in numbers like 1_000_000 are only for reading; Python ignores them. abs, max and min are built-in functions you can use without importing anything.
Practice exercises
- Work out how many whole weeks and extra days there are in 100 days, using
//and%. - Print the last digit of
987654321with%. - Calculate the area of a circle with radius 7 using
3.14159 * r ** 2, rounded to 2 decimals. - Print
2 ** 64and count its digits withlen(str(2 ** 64)).