Basic Math Operations
Python's math operators are like the buttons on a calculator: + (add), - (subtract), * (multiply), / (divide). But Python can do more than a calculator!
Python can perform all basic arithmetic operations, just like a calculator – but it's much more powerful because you can combine operations, store results in variables, and use them in complex expressions.
**The main arithmetic operators are:**
- `+` Addition: `5 + 3` = 8
- `-` Subtraction: `10 - 4` = 6
- `*` Multiplication: `7 * 6` = 42
- `/` Division: `15 / 4` = 3.75 (always returns a float)
- `//` Floor division (integer division): `15 // 4` = 3 (discards remainder)
- `%` Modulo (remainder): `15 % 4` = 3
- `**` Exponentiation (power): `2 ** 3` = 8 (2 to the power of 3)
**Order of operations (PEMDAS):**
Python follows the standard mathematical order:
1. Parentheses `()`
2. Exponents `**`
3. Multiplication `*`, Division `/`, Floor division `//`, Modulo `%` (left to right)
4. Addition `+`, Subtraction `-` (left to right)
Examples:
- `2 + 3 * 4` → `2 + 12` = 14 (multiplication first)
- `(2 + 3) * 4` → `5 * 4` = 20 (parentheses first)
- `2 ** 3 ** 2` → `2 ** (3 ** 2)` = 2 ** 9 = 512 (right‑to‑left for exponents)
**Important notes about division:**
- Regular division `/` always returns a float, even if the result is a whole number: `10 / 2` → `5.0`
- Floor division `//` returns an integer (truncates toward negative infinity): `7 // 3` → `2`, `-7 // 3` → `-3`
- Modulo `%` returns the remainder: `17 % 5` → `2`
**Using math with variables:**
You can store results in variables and reuse them:
```python
a = 10
b = 3
sum_ab = a + b
product_ab = a * b
```
**Augmented assignment operators (shortcuts):**
These let you update a variable in place:
- `x += 5` is short for `x = x + 5`
- `x -= 2` → `x = x - 2`
- `x *= 3` → `x = x * 3`
- `x /= 4` → `x = x / 4`
- `x //= 2` → `x = x // 2`
- `x %= 3` → `x = x % 3`
- `x **= 2` → `x = x ** 2`
**Common beginner mistakes:**
- Using `=` (assignment) instead of `==` (comparison) in conditions.
- Forgetting that `/` returns a float, even when you expect an integer.
- Assuming `**` is `^` (caret) – `^` is actually the bitwise XOR operator.
- Integer overflow? Python handles arbitrarily large integers, no problem.
- Mixing integers and floats in division – result is always float.
**Real‑world applications:**
- Calculating totals, discounts, and taxes in e‑commerce.
- Converting units (temperature, distance, currency).
- Game development (score updates, damage calculations).
- Data analysis (averages, percentages, growth rates).
- Geometry and physics simulations.
**Practice exercises:**
1. Write a program that calculates the area of a rectangle (length × width).
2. Convert Celsius to Fahrenheit: `F = (C * 9/5) + 32`.
3. Calculate the number of seconds in a year (365 days) using multiplication.
4. Find the remainder when 237 is divided by 13 using `%`.
5. Compute `2 ** 10` – what is this number? (Hint: 1024, known as 1 kilobyte).
# ========== EXAMPLE 1: Basic Arithmetic ==========
print("=== Example 1: Basic Math Operations ===")
apples = 5
oranges = 3
total_fruits = apples + oranges
print(f"Total fruits: {total_fruits}")
apples_per_box = 10
boxes = 4
total_apples = apples_per_box * boxes
print(f"Total apples: {total_apples}")
pizza_slices = 8
people = 3
slices_per_person = pizza_slices / people
remaining_slices = pizza_slices % people
print(f"Each person gets: {slices_per_person} slices")
print(f"Remaining slices: {remaining_slices}")
print()
# ========== EXAMPLE 2: Order of Operations (PEMDAS) ==========
print("=== Example 2: Order of Operations ===")
result1 = 2 + 3 * 4
result2 = (2 + 3) * 4
result3 = 2 ** 3 + 1
result4 = 2 ** (3 + 1)
print(f"2 + 3 * 4 = {result1}")
print(f"(2 + 3) * 4 = {result2}")
print(f"2 ** 3 + 1 = {result3}")
print(f"2 ** (3 + 1) = {result4}")
print()
# ========== EXAMPLE 3: Augmented Assignment & Practical Uses ==========
print("=== Example 3: Augmented Assignment and Real‑World Math ===")
# Shopping cart example
price = 100
tax_rate = 0.08
price += 25 # add another item
print(f"Subtotal after adding item: ${price}")
tax = price * tax_rate
total = price + tax
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
# Countdown example
count = 5
print(f"\nStarting countdown: {count}")
count -= 1
print(f"After subtract 1: {count}")
count *= 2
print(f"After doubling: {count}")
count //= 3
print(f"After floor division by 3: {count}")
→ Run this code interactively