Math
Add, subtract, multiply, divide, and more.
Math operators
| Symbol | What it does | Example |
|---|---|---|
| + | Add | 7 + 2 gives 9 |
| - | Subtract | 7 - 2 gives 5 |
| * | Multiply | 7 * 2 gives 14 |
| / | Divide, always gives a decimal | 7 / 2 gives 3.5 |
| // | Divide and drop the decimal | 7 // 2 gives 3 |
| % | Remainder after dividing | 7 % 2 gives 1 |
| ** | Raise to a power | 7 ** 2 gives 49 |
When the answer is a decimal
A decimal in, a decimal out
If either number has a decimal point, the answer has one too. And / always gives a decimal, even when it divides evenly.
total = 50 + 4.0
print(total)
print(6 / 3)Output
54.0 2.0
Drop the decimal, or keep the remainder
Divide and drop the decimal
// divides, then chops off everything after the decimal point.
print(5 / 3)
print(5 // 3)Output
1.6666666666666667 1
The remainder with %
3 goes into 5 one time, with 2 left over. % gives the left over part.
print(5 % 3)Output
2
Even or odd
An even number divided by 2 has nothing left over, so % 2 gives 0.
num = 9
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")Output
9 is odd.