Lesson 5 of 30 · Working With Data
Numbers and Math
Do maths in Python: add, subtract, multiply, divide, find remainders and powers. Learn operator order, rounding and shortcuts like +=.
- 7 min read
- Beginner
- Reviewed
- Python's seven arithmetic operators
- The order in which Python does calculations
- How to round numbers and update a variable with shortcuts
Python as a calculator
Python can do everything a calculator can. The symbols are called operators.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide | 7 / 2 | 3.5 |
// | Divide and round down | 7 // 2 | 3 |
% | Remainder | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
Run them and change the numbers.
print(7 + 2) print(7 - 2) print(7 * 2) print(7 / 2) print(7 // 2) print(7 % 2) print(7 ** 2)
Three operators that surprise beginners
Division always gives a float. Even when the answer is a whole number, / returns a decimal.
print(10 / 2) print(type(10 / 2))
Floor division // throws away the decimal part. Use it when you need a whole number, such as how many full boxes you can fill.
The remainder % gives what is left over after dividing. It is very handy for checking whether a number is even: an even number has a remainder of 0 when divided by 2.
eggs = 50
box_size = 12
print("Full boxes:", eggs // box_size)
print("Eggs left over:", eggs % box_size)
print("Is 50 even?", 50 % 2 == 0)Order of operations
Python follows the same order as maths: powers first, then multiplication and division, then addition and subtraction. Use brackets to change the order or simply to make your meaning clear.
print(2 + 3 * 4) print((2 + 3) * 4)
Maths with variables
Operators work on variables just as they do on numbers.
price = 250
quantity = 4
discount = 100
total = price * quantity - discount
print("Total to pay:", total)Updating a variable: the shortcut operators
Adding to a variable is so common that Python has a shortcut. score += 5 means the same as score = score + 5.
score = 10 score += 5 print(score) score -= 3 print(score) score *= 2 print(score)
Rounding
round() rounds a number. Give it a second value to choose how many decimal places to keep.
pi = 3.14159265 print(round(pi)) print(round(pi, 2)) print(round(7 / 3, 1))
Calculate the average of the three scores and print Average: 85.0.
maths = 80 science = 90 english = 85 # Calculate the average of the three scores # and print it so the output is exactly: Average: 85.0
What is the result of 17 % 5 ?
Summary
+,-,*,/,//,%and**are the arithmetic operators./always returns a float.//rounds down.%gives the remainder.- Powers come first, then
*and/, then+and-. Brackets override the order. +=,-=and*=update a variable in place.round()tidies up decimals.
Next, you will learn to work with text in much more depth.
Finished reading? Tick it off to track your progress.