Loading...
Loading...
Perform calculations with integers and floats
Python can do math ā addition, subtraction, multiplication, division, and more. The math operators work much like a calculator, but with the power to use variables so your calculations adapt to changing data.
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Integer division: 3 (drops decimal)
print(a % b) # Modulo (remainder): 1
print(a ** b) # Exponent: 10³ = 1000| Operator | Name | What it does | Example | Result |
|---|---|---|---|---|
| `+` | Addition | Adds two numbers | `5 + 3` | `8` |
| `-` | Subtraction | Subtracts right from left | `10 - 4` | `6` |
| `*` | Multiplication | Multiplies | `6 * 7` | `42` |
| `/` | Division | Always returns a float | `10 / 3` | `3.333...` |
| `//` | Integer division | Drops the decimal | `10 // 3` | `3` |
| `%` | Modulo | Remainder after division | `10 % 3` | `1` |
| `**` | Exponent | Raises to power | `2 ** 3` | `8` |
Python follows the standard order of operations (PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction):
result = (5 + 3) * 2 ** 2
# Step 1: Parentheses ā (5 + 3) = 8
# Step 2: Exponent ā 2 ** 2 = 4
# Step 3: Multiplication ā 8 * 4 = 32
print(result) # 32Almost every program does some form of math:
The modulo operator % is especially useful ā it tells you if a number is even (number % 2 == 0) or helps cycle through options.
| ā Wrong | Why | ā Right |
|---|---|---|
| `result = 10 / 3` expecting `3` | `/` always gives a float | Use `//` for integer: `10 // 3` |
| `price = 5 + 3 * 2` expecting `16` | Multiplication happens before addition! | Use parentheses: `(5 + 3) * 2` |
| `result = "5" + 3` | Can't add string + number ā TypeError | Convert first: `int("5") + 3` |
| `print(2 ** 3 * 4)` | `**` has higher precedence than `*` | Know your operator precedence |
Create two variables x = 15 and y = 4. Calculate and print:
x = 15 y = 4 print(x + y) print(x / y) print(x % y) print(x ** y)