← Home

018. Arithmetic Operators

Basic math operations on numeric types

018. Arithmetic Operators

RAM Manager — Memory Usage Stats

Aryan’s RAM manager needs to report memory statistics. Given the total RAM and the amount currently used, it should calculate:

  • used_percent: percentage of RAM in use
  • free_mb: free memory in MB
  • per_process_share: how many MB each process would get if RAM were shared equally

He writes ram_stats(total_mb, used_mb, num_processes), but the used-percent formula adds instead of multiplies — used_mb + 100 instead of used_mb * 100 — so a machine with 800 MB used out of 1000 MB reports 90% usage instead of 80%.

The lesson: + and * look similar in a formula but produce wildly different results. Always double-check which arithmetic operation a formula actually requires.


💡 Fun fact: Python’s arithmetic operators follow the same PEMDAS/BODMAS precedence as C (and mathematics), but with one key difference: / always returns a float in Python 3. In Python 2, 5 / 2 gave 2 (integer division), a behaviour change that was one of the major motivations for Python 3.

⚠️ Watch out: Accidentally writing + where * is needed (or vice versa) produces a result that looks plausible but is numerically wrong — the code will not crash, it will just silently give the wrong answer. Always test formulas with known values where you can verify the expected output by hand.

🤔 Think about it: The tip formula bill_amount * tip_percent / 100 relies on Python’s operator precedence to evaluate * before /. Would adding parentheses change the result, and when does making precedence explicit with parentheses become a good habit?

Learning objectives

  • Use +, -, *, / for basic arithmetic
  • Apply correct operator to a formula
  • Understand that / returns float

Key concepts

  • arithmetic operators
  • /
  • operator precedence

Try it

Concept detail

Python arithmetic operators: + (add), - (subtract), * (multiply), / (divide, returns float), // (floor divide), % (modulo), ** (exponentiate), - (unary negate). Operator precedence (PEMDAS/BODMAS): ** first, then *, /, //, %, then +, -. Mixed arithmetic: int + float = float, int + int = int, float + float = float. Division always returns float: 4/2 = 2.0 (not 2!). Use // for integer result: 4//2 = 2.

Solution

def calculate_tip(bill_amount, tip_percent):
    tip_amount = bill_amount * tip_percent / 100
    total = bill_amount + tip_amount
    return tip_amount, total

def split_per_person(bill, tip_pct, people):
    tip, total = calculate_tip(bill, tip_pct)
    return total / people

Tests

def test_tip_amount():
    tip, total = calculate_tip(100, 20)
    assert tip == 20.0

def test_total():
    tip, total = calculate_tip(100, 20)
    assert total == 120.0

def test_tip_fifteen_percent():
    tip, total = calculate_tip(200, 15)
    assert tip == 30.0

def test_split_three_ways():
    result = split_per_person(90, 10, 3)
    assert abs(result - 33.0) < 0.001

Resources