30 min read
Putting It Together: the Shop Till
A complete program using variables, input, decisions, a loop and functions — planned with a flowchart, then coded and tested.
The Brief
Step 1 — Plan
| Inputs, processing, outputs | |
|---|---|
Step 2 — the flowchart
Read this flowchart as text
- Terminator: Start (then → total = 0)
- Process: total = 0 (then → INPUT price)
- Input/output: INPUT price (then → price > 0?)
- Decision: price > 0? (Yes → INPUT quantity; No → to_pay = apply_discount(total))
- Input/output: INPUT quantity (then → total = total + line_total(price, quantity))
- Predefined process: to_pay = apply_discount(total) (then → print_receipt(total, to_pay))
- Predefined process: total = total + line_total(price, quantity) (then → INPUT price)
- Predefined process: print_receipt(total, to_pay) (then → Stop)
- Input/output: INPUT price (then → price > 0?)
- Terminator: Stop
Step 3 — The Code
till.pyPython
# till.py - Perera Corner Mart till# Adds up items until a price of 0, applies a 10% discount over LKR 5,000,# and prints a receipt. DISCOUNT_LIMIT = 5000DISCOUNT_RATE = 0.10 def line_total(price, quantity): return price * quantity def apply_discount(total): if total > DISCOUNT_LIMIT: return total * (1 - DISCOUNT_RATE) return total def print_receipt(subtotal, to_pay): print("-" * 30) print(f"{'Subtotal':<18}{subtotal:>12,.2f}") print(f"{'Discount':<18}{subtotal - to_pay:>12,.2f}") print(f"{'AMOUNT TO PAY':<18}{to_pay:>12,.2f}") print("-" * 30) print("Thank you for shopping!") subtotal = 0price = float(input("Price (0 to finish): ")) while price > 0: quantity = int(input("Quantity: ")) subtotal += line_total(price, quantity) price = float(input("Price (0 to finish): ")) to_pay = apply_discount(subtotal)print_receipt(subtotal, to_pay)Expected output
Price (0 to finish): 1450 Quantity: 3 Price (0 to finish): 480 Quantity: 2 Price (0 to finish): 0 ------------------------------ Subtotal 5,310.00 Discount 531.00 AMOUNT TO PAY 4,779.00 ------------------------------ Thank you for shopping!
Step 4 — Test
| Test plan | |||
|---|---|---|---|
Practice
The subtotal is exactly 5,000. What does apply_discount return?
More lessons in Python Programming · Next: Debugging Your Programs · Previous: Functions
