Numbers and math
Python makes a very good calculator. In this lesson you will use the two kinds of numbers, int and float, and the operators that work on them. Every result below is worked out live in your browser.
The basic operators
| Operator | Does | Example | Result |
|---|---|---|---|
+ | add | 7 + 3 | 10 |
- | subtract | 7 - 3 | 4 |
* | multiply | 7 * 3 | 21 |
/ | divide | 7 / 2 | 3.5 |
** | power | 7 ** 2 | 49 |
1print(7 + 3)2print(7 - 3)3print(7 * 3)4print(7 / 3)5print(2 ** 10)
10 4 21 2.3333333333333335 1024
Spaces around operators are optional, but they make code easier to read. Note * for multiply, not x, and ** for "to the power of".
Three ways to divide
/ always gives a float, even when the division comes out even. Two more operators split a division into its whole part and what is left over:
| Operator | Name | 17 and 5 |
|---|---|---|
/ | division | 3.4 |
// | floor division: how many whole times | 3 |
% | remainder (also called modulo) | 2 |
1print(6 / 3)2lamps = 173per_street = 54print("Full streets:", lamps // per_street)5print("Lamps left over:", lamps % per_street)6print(10 % 2, 11 % 2)
2.0 Full streets: 3 Lamps left over: 2 0 1
% is handy more often than you might think: a number is even when % 2 gives 0, and % 60 turns a count of minutes into "minutes past the hour".
What does this print?
1print(20 // 6, 20 % 6) 6 fits into 20 three whole times (that's 18), with 2 left over. // gives the 3, % gives the 2.
Order of operations
Python follows the same order as school math. Higher in the table goes first; on the same row, left to right, except **, which goes right to left: 2 ** 3 ** 2 is 2 ** 9.
| Order | Operators |
|---|---|
| 1 | ( ) parentheses |
| 2 | ** |
| 3 | *, /, //, % |
| 4 | +, - |
1print(2 + 3 * 4)2print((2 + 3) * 4)3print(2 * 3 ** 2)4print(-2 ** 2)
14 20 18 -4
The last one surprises people: ** goes before the minus sign, so it means -(2 ** 2). When in doubt, add parentheses. They cost nothing and make your meaning clear.
What does this print?
1print(10 - 4 / 2) / goes first: 4 / 2 is 2.0. Then 10 - 2.0 is 8.0. It is a float because / always gives one.
int and float together
You can mix the two kinds freely. If either side is a float, the result is a float:
1print(3 + 2.0)2print(type(3 + 2.0))3print(0.1 + 0.2)4print(1.1 * 3)
5.0 <class 'float'> 0.30000000000000004 3.3000000000000003
The last two are not bugs in Python. Computers store floats in binary, and most decimals, like 0.1, cannot be stored exactly, the way 1/3 cannot be written exactly as 0.333... The error is tiny, but it shows when you print. Whole numbers (int) are always exact.
Rounding
round(x) rounds to a whole number; round(x, 2) keeps two decimal places. To round only how a number is shown, put :.2f after it in an f-string:
1share = 2 / 32print(share)3print(round(share, 2))4print(round(share))5print(f"Each gets {share:.2f}")6print(round(2.5), round(3.5))
0.6666666666666666 0.67 1 Each gets 0.67 2 4
Tip: round() sends an exact half to the nearest even number, so round(2.5) is 2. That keeps totals fair when you round many values. For money, the usual habit is to keep the full value and format it with :.2f when printing.
Changing a variable by an amount
Adding to a variable is so common that it has a short form. oil += 5 means oil = oil + 5:
| Short | Means |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
1oil = 102oil -= 33oil += 54oil *= 25print(oil)
24
Handy built-in functions
1print(abs(-7))2print(min(4, 9, 2))3print(max(4, 9, 2))4print(sum([4, 9, 2]))
7 2 9 15
abs drops the minus sign; min and max pick the smallest and largest of any number of values. sum adds up a whole list of numbers; the square brackets make a list, which you will meet properly in lesson 9.
The math module
More math lives in the math module. import math once at the top, then write math. before each name:
1import math2print(math.sqrt(16))3print(math.pi)4print(math.floor(3.7), math.ceil(3.2))
4.0 3.141592653589793 3 4
| Name | Gives |
|---|---|
math.sqrt(x) | square root (a float) |
math.pi | the number pi |
math.floor(x) | round down to a whole number |
math.ceil(x) | round up to a whole number |
math.ceil is the one to use when you need "enough": 17 lamps in boxes of 5 need math.ceil(17 / 5), which is 4 boxes.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Hours and minutes
✓Turn minutes into hours and minutes, and print the line below.
2 hours 5 minutes
1minutes = 1252print(minutes)
A tidy total
✓Three lamps cost 1.10 each. The total prints with a tiny float error. Show it with exactly two decimals.
Total: 3.30
1price = 1.102count = 33print(f"Total: {price * count}")
Fix the average
✓This should print the average of the three scores, but the answer is wrong. Fix it.
8.0
1a = 72b = 83c = 94print(a + b + c / 3)
What you learned
+ - * /work as in math;**is a power./always gives a float;//gives the whole part and%the remainder.**goes first, then* / // %, then+ -; parentheses override everything.- Mixing an
intwith afloatgives afloat; floats can be very slightly off. round(x, 2)rounds;f"{x:.2f}"shows two decimals.x += 1is short forx = x + 1.abs,min,max,sumare built in;import mathgivessqrt,pi,floor,ceil.