Numbers and Math Operations
Learn how to do calculations in Python, work with different types of numbers, and understand operator precedence.
The seven operators
Python can do all the math you learned in school. The symbols you use are called operators, and the values they work on are called operands. In 10 + 3, the plus is the operator and 10 and 3 are the operands. Here are the seven you need:
print(10 + 3) # Addition: 13
print(10 - 3) # Subtraction: 7
print(10 * 3) # Multiplication: 30
print(10 / 3) # Division: 3.3333333333333335
print(10 // 3) # Floor division: 3 (removes the decimal)
print(10 % 3) # Modulo: 1 (remainder after dividing)
print(10 ** 3) # Exponent: 1000 (10 to the power of 3)
Notice that multiplication uses *, not an x, and an exponent uses two stars **. The last three are the ones that feel new, so the next cards slow down and explain each of them.
Python also works with negative numbers and with decimals in exactly the same way, for example -4 + 10 gives 6 and 2.5 * 4 gives 10.0.
Regular vs floor division
Regular division (single slash) always gives a float, even when the numbers divide evenly:
print(10 / 2) # 5.0, not 5
If you want a whole number with no decimal, use floor division (double slash):
print(10 // 2) # 5
print(10 // 3) # 3, the 0.33 part is removed, not rounded
Floor division always rounds down, toward the smaller number. So 10 // 3 is 3, and also 7 // 2 is 3, not 4. This is useful when you want complete groups. For example, how many full boxes of 6 eggs can you fill from 20 eggs?
eggs = 20
boxes = eggs // 6
print(boxes) # 3
A tricky detail: with negative numbers, floor division rounds down, so -7 // 2 gives -4. You will not need that often, but it helps to know it is not a bug.
Modulo is the remainder
The modulo operator (%) gives you the remainder after division. It is more useful than it sounds. For example, you can check if a number is even or odd:
print(10 % 2) # 0, no remainder, so 10 is even
print(7 % 2) # 1, remainder is 1, so 7 is odd
print(15 % 4) # 3, 15 divided by 4 is 3 remainder 3
Floor division and modulo are partners. Together they tell the whole story of a division. 15 // 4 is 3 whole groups, and 15 % 4 is 3 left over, because 4 times 3 plus 3 is 15.
Here are the most common uses of modulo:
- Even or odd:
number % 2 == 0means even - Every Nth item:
i % 5 == 0is true for every fifth number - Wrapping around: the minutes on a clock go back to 0 after 59, and
minutes % 60does that - Divisibility: if
a % b == 0, thenadivides evenly byb
total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{hours} hours and {minutes} minutes") # 2 hours and 15 minutes
Order of operations
Python follows the same rules you learned in school. Exponents first, then multiplication and division, then addition and subtraction. If two operators have the same level, Python goes from left to right. Use parentheses to control the order:
print(2 + 3 * 4) # 14, multiplication first, then addition
print((2 + 3) * 4) # 20, parentheses first
print(2 ** 3 + 1) # 9, exponent first: 8 + 1
When in doubt, add parentheses. They cost nothing and make your intent clear to anyone reading. Compare these two lines, which give different answers:
average = 10 + 20 + 30 / 3 # 40.0, wrong!
average = (10 + 20 + 30) / 3 # 20.0, correct
In the first line the division happens first, so only 30 is divided by 3. The brackets in the second line force the addition to happen first. This is a very common bug in beginner programs.
Math with variables and shortcuts
Math works with variables the same way as with plain numbers:
length = 10
width = 5
area = length * width
print(area) # 50
A very common pattern is to take a variable, do math on it, and store the result back in the same variable. There is a shorthand for that:
score = 100
score = score + 10 # regular way
print(score) # 110
score += 10 # shorthand, same result
print(score) # 120
score -= 5 # subtract and store
print(score) # 115
score *= 2 # multiply and store
print(score) # 230
There are shorthand versions for the other operators too: /=, //=, %= and **=. Read score += 10 as "add 10 to score". You will use += constantly when you count things in loops.
The math module and round()
Python has a built-in module called math that gives you more advanced math tools. A module is a toolbox someone already built for you. To use it, write import math at the top of your file:
import math
print(math.sqrt(16)) # Square root: 4.0
print(math.pi) # Pi: 3.141592653589793
print(math.floor(3.7)) # Round down: 3
print(math.ceil(3.2)) # Round up: 4
The built-in round() function works without importing anything:
print(round(3.7)) # 4
print(round(3.14159, 2)) # 3.14, round to 2 decimal places
Other handy built-in functions are abs() for the size of a number without its sign (abs(-5) is 5), min() and max() for the smallest and largest value, and pow(2, 3), which is the same as 2 ** 3.
Ints, floats and surprises
When you mix an int and a float in one calculation, Python gives a float. That makes sense, because a float can hold the decimals and an int cannot.
print(5 + 2.0) # 7.0
print(2 * 3.5) # 7.0
print(7 / 7) # 1.0, division always gives a float
Floats can also surprise you. Computers store them in a way that is very close but not always exact:
print(0.1 + 0.2) # 0.30000000000000004
This is not a Python bug. Every programming language has it. It only matters when you compare floats or need exact money math. For display, use round() or an f-string with :.2f.
total = 0.1 + 0.2
print(round(total, 2)) # 0.3
print(f"{total:.2f}") # 0.30
You can also write big numbers with underscores to make them easier to read. Python ignores the underscores: population = 7_900_000_000.
A worked example: splitting a bill
Let us put several ideas together. Four friends split a restaurant bill and add a tip. This uses variables, math operators, parentheses, round() and an f-string.
bill = 84.00
tip_percent = 15
people = 4
tip = bill * tip_percent / 100
total = bill + tip
each = total / people
print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Each person pays: {each:.2f}")
Tip: 12.60
Total: 96.60
Each person pays: 24.15
Walk through it step by step. The tip is 15 percent of 84. We add it to the bill, then divide by the number of people. If you change one variable at the top, every result below updates by itself. That is the power of variables.
Key takeaways
- The operators are
+ - * / // % ** /always gives a float.//rounds down to a whole number%gives the remainder and is perfect for checking even or odd- Python uses school order: exponents, then multiplication and division, then addition and subtraction. Use brackets when unsure
+=,-=,*=update a variable in one stepimport mathunlockssqrt,pi,floorandceil, andround()is built in- Floats are close, not exact, so round when you display them