Python — Variables, integer division, and formatting
Python’s // operator gives the floor quotient and % gives the corresponding remainder. For 125 cents, these operations separate 1 dollar from 25 cents.
A simple example
Change a stored number
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
n = 2
n += 1
print(n)
3
Calculate a receipt in cents
Assignments bind names to integer objects. Floor division and remainder separate dollars from cents. The format specification 02d pads a one-digit remainder with a leading zero.
A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
price_cents = 125
quantity = 3
delivery_cents = 50
total = price_cents * quantity + delivery_cents
print(f"{total // 100}.{total % 100:02d}")
4.25
Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.
Try it yourself
What happens if each item costs 101 cents?
Check your answer
Three items plus delivery cost 353 cents, so the output becomes 3.53.