smartyfy.mrindigi.com

Python Master Course V2 — 011. Arithmetic Operators and Reliable Calculations

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 02 · LESSON 011 OF 200

Arithmetic Operators — From Expressions to Reliable Calculations

Level: Beginner to intermediate foundations · Study: 60–90 minutes · Prerequisite: Lesson 010 — Foundations Capstone

← Course hub

1. Video lesson

Video not yet available. This area is reserved for a verified Lesson 011 video URL or embedded player. All written material is available below.

2. Learning outcomes

  • Explain addition, subtraction, multiplication, true division, floor division, modulo and exponentiation.
  • Predict operator precedence and use parentheses to communicate intent.
  • Distinguish integer, float and Decimal results, including negative-number edge cases.
  • Validate numerical inputs and avoid division by zero.
  • Build and test a practical shipping and stock calculation utility.

3. Concepts and mental models

An arithmetic expression combines values and operators to produce a result. Python evaluates an expression before assigning its value or passing it to print(). The seven core arithmetic operators are +, -, *, /, //, % and **. Unary - negates a value.

Division: / returns a floating-point result for ordinary integer operands; // rounds the quotient toward negative infinity, not toward zero. Modulo satisfies a == (a // b) * b + (a % b) for integer operands with nonzero divisor.

Precedence: exponentiation binds more tightly than unary minus: -2**2 means -(2**2). Multiplication, division, floor division and modulo bind more tightly than addition and subtraction. Use parentheses whenever the intended grouping may be unclear.

Numeric types: int represents arbitrary-precision integers, while float uses approximate binary floating-point. For financial examples, use Decimal constructed from strings with an explicit rounding rule.

4. Progressive runnable examples

Setup: Python 3.10 or later. Save each independent example as lesson011_example.py and run python lesson011_example.py (or python3). Outputs below are expected outputs, not claims of execution on Smartyfy.

Example A — Four basic operations

a, b = 17, 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)

Expected:

22
12
85
3.4

Example B — Floor division and remainder

for a, b in [(17, 5), (-17, 5), (17, -5)]:
    q, r = a // b, a % b
    print(a, b, q, r, q * b + r == a)

Expected:

17 5 3 2 True
-17 5 -4 3 True
17 -5 -4 -3 True

The remainder takes the divisor’s sign (unless zero), which matters when designing cycles and bucket assignments.

Example C — Precedence

print(2 + 3 * 4)
print((2 + 3) * 4)
print(-2**2)
print((-2)**2)
print(2**3**2)

Expected:

14
20
-4
4
512

Exponentiation groups right-to-left, so the last expression is 2**(3**2).

Example D — Exact decimal arithmetic

from decimal import Decimal, ROUND_HALF_UP
price = Decimal("19.95")
quantity = 3
tax_rate = Decimal("0.05")
subtotal = price * quantity
tax = (subtotal * tax_rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(f"Subtotal: {subtotal:.2f}")
print(f"Tax: {tax:.2f}")
print(f"Total: {subtotal + tax:.2f}")

Expected:

Subtotal: 59.85
Tax: 2.99
Total: 62.84

Example E — Guard against zero

total_marks = 180
subjects = 0
if subjects == 0:
    print("Cannot calculate an average without subjects.")
else:
    print(total_marks / subjects)

Expected: Cannot calculate an average without subjects.

Example F — Unit conversion

total_minutes = 137
hours, minutes = divmod(total_minutes, 60)
print(f"{hours} hours, {minutes} minutes")

Expected: 2 hours, 17 minutes. divmod(a,b) conveniently returns (a // b, a % b).

5. Guided real-world project — Packing and shipping estimator

Scenario: A stationery business packs notebooks into boxes. Given a valid positive quantity, box capacity and unit price, calculate full boxes, remaining items, boxes required and merchandise cost. Use integer arithmetic for stock and Decimal for currency.

Business rule: A partially filled box still counts as one shipping box. For positive integers, ceiling division can be written (quantity + capacity - 1) // capacity.

from decimal import Decimal, InvalidOperation

print("=== Packing and Shipping Estimator ===")
try:
    quantity = int(input("Notebook quantity: ").strip())
    capacity = int(input("Items per box: ").strip())
    price = Decimal(input("Unit price (INR): ").strip())
except (ValueError, InvalidOperation):
    print("Invalid numeric input.")
else:
    if quantity <= 0 or capacity <= 0:
        print("Quantity and capacity must be positive.")
    elif not price.is_finite() or price < 0:
        print("Price must be a finite nonnegative amount.")
    else:
        full_boxes, remaining = divmod(quantity, capacity)
        boxes_required = (quantity + capacity - 1) // capacity
        merchandise_total = price * quantity
        print(f"Full boxes: {full_boxes}")
        print(f"Loose items: {remaining}")
        print(f"Boxes required: {boxes_required}")
        print(f"Merchandise total: INR {merchandise_total:.2f}")

Sample input: quantity 23, capacity 8, price 12.50.

Full boxes: 2
Loose items: 7
Boxes required: 3
Merchandise total: INR 287.50

Walkthrough: 23 // 8 is 2 complete boxes, 23 % 8 is 7 remaining items, and ceiling division gives 3 total boxes. Multiplying Decimal("12.50") by 23 gives 287.50.

Boundary tests: quantity 8/capacity 8 gives one box and zero loose items; quantity 9/capacity 8 gives two boxes; capacity zero is rejected; negative price is rejected; invalid text is caught.

6. Common mistakes and professional practices

  • Confusing / and //: use true division for ratios and floor division for integer grouping, with attention to negative operands.
  • Division by zero: validate divisors before calculation.
  • Float for money: use Decimal strings when exact decimal rounding matters.
  • Ignoring parentheses: write explicit grouping for maintainable expressions.
  • Assuming % is always positive: test negative divisors.
  • Trusting user input: convert in try/except and check business constraints separately.
  • Unclear units: use descriptive variable names such as items_per_box and unit_price_inr.

7. Guided exercises and independent challenge

  1. Predict 29 // 6 and 29 % 6; verify by running Python.

    Hint: quotient and remainder

    Find the largest whole number of groups of six, then count the items left over.

    Worked answer: quotient and remainder
    quotient, remainder = divmod(29, 6)
    print(quotient)
    print(remainder)
    print(29 == quotient * 6 + remainder)

    Expected output:

    4
    5
    True

    Four groups use 24 items and leave five. The identity a == (a // b) * b + (a % b) checks that both results fit together.

  2. Explain why -7 // 3 is -3 rather than -2.

    Hint: floor division with negatives

    Floor moves toward negative infinity, not toward zero.

    Worked answer: floor division with negatives
    print(-7 / 3)
    print(-7 // 3)
    print(-7 % 3)
    print((-7 // 3) * 3 + (-7 % 3))

    Expected output:

    -2.3333333333333335
    -3
    2
    -7

    The floor of approximately -2.33 is -3. A remainder of 2 preserves the division identity. Truncating toward zero would give a different quotient.

  3. Calculate the number of 12-seat vans needed for 49 passengers.

    Hint: vans for 49 passengers

    A partly occupied van still counts; use ceiling division for positive integers.

    Worked answer: vans for 49 passengers
    passengers = 49
    seats_per_van = 12
    vans = (passengers + seats_per_van - 1) // seats_per_van
    unused_seats = vans * seats_per_van - passengers
    print(vans)
    print(unused_seats)

    Expected output:

    5
    11

    Four vans carry only 48 passengers. The fifth van is necessary even though it has eleven unused seats. Check 48 passengers as a boundary: that case needs exactly four vans.

  4. Modify the project to include a fixed Decimal shipping cost per box.

    Hint: shipping cost per box

    Charge every required box, including the partially filled one; keep currency values as Decimal.

    Worked answer: shipping cost per box
    from decimal import Decimal
    
    quantity = 23
    capacity = 8
    unit_price = Decimal("12.50")
    shipping_per_box = Decimal("15.00")
    boxes_required = (quantity + capacity - 1) // capacity
    merchandise_total = unit_price * quantity
    shipping_total = shipping_per_box * boxes_required
    print(boxes_required)
    print(shipping_total)
    print(merchandise_total + shipping_total)

    Expected output:

    3
    45.00
    332.50

    Three boxes cost ₹45.00 to ship. Adding that to ₹287.50 of merchandise gives ₹332.50. Add these calculations inside the project’s accepted-input branch, after its validation.

  5. Reject a unit price with more than two decimal places.

    Hint: price decimal places

    Reject non-finite values first, then inspect the Decimal exponent.

    Worked answer: price decimal places
    from decimal import Decimal
    
    for text in ["12.50", "12.5", "12.500", "NaN", "-1.00"]:
        price = Decimal(text)
        valid = (price.is_finite() and price >= 0
                 and price.as_tuple().exponent >= -2)
        print(text, valid)

    Expected output:

    12.50 True
    12.5 True
    12.500 False
    NaN False
    -1.00 False

    An exponent of -2 means two decimal places. This policy rejects a third supplied place even when it is a trailing zero. Keep the project’s conversion-error handler for malformed text; formatting a value to two decimals is not validation.

  6. Build a time converter from total seconds into hours, minutes and seconds using divmod.

    Hint: hours, minutes and seconds

    Split into hours and remaining seconds, then split that remainder into minutes and seconds.

    Worked answer: hours, minutes and seconds
    total_seconds = 7384
    hours, remainder = divmod(total_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    print(hours, minutes, seconds)
    print(hours * 3600 + minutes * 60 + seconds == total_seconds)

    Expected output:

    2 3 4
    True

    The first split leaves 184 seconds; the second produces three minutes and four seconds. Require a nonnegative whole-number input for this duration policy.

Advanced challenge: extend the packing estimator to compare two box sizes and choose the option with the fewest boxes. For a tie, choose the one with less unused capacity. Print the decision and test quantities 1, 8, 9, 16 and 17.

8. Knowledge check with answers

  1. What is 7 / 2? Answer: 3.5.
  2. What is 7 // 2? Answer: 3.
  3. What is 7 % 2? Answer: 1.
  4. What is 3 + 2 * 5? Answer: 13.
  5. What is (3 + 2) * 5? Answer: 25.
  6. Why construct Decimal from a string? Answer: to avoid importing an approximate binary floating-point value.

9. Mastery checkpoint

Before continuing, you should be able to explain all seven arithmetic operators, calculate a quotient and remainder, predict precedence, reject invalid divisors, and adapt the packing estimator to a new business rule. Review the examples if any of these are unclear.

Lesson summary: Arithmetic operators become reliable engineering tools when paired with appropriate numeric types, clear grouping, input validation and boundary testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.