Skip to content

script_10.py - Discount Calculator

Code

Python
#!/usr/bin/env python3
"""Discount calculator"""

total = float(input("Enter purchase total: "))

if total >= 100:
    discount = total * 0.20
    print(f"20% discount applied: ${discount:.2f}")
    print(f"Final price: ${total - discount:.2f}")
elif total >= 50:
    discount = total * 0.10
    print(f"10% discount applied: ${discount:.2f}")
    print(f"Final price: ${total - discount:.2f}")
else:
    print(f"No discount. Total: ${total:.2f}")

Explanation

Line 4: total = float(input("Enter purchase total: ")) - input() returns string type (str) - float() converts to floating-point type for decimal currency values - total variable stores the float value

Line 7: discount = total * 0.20 - * is multiplication operator - 0.20 is a float literal representing 20% - discount variable stores the calculated discount amount (also float type) - Result is 20% of the total

Line 8: print(f"20% discount applied: ${discount:.2f}") - f-string with format specifier - {discount:.2f} means format the float with 2 decimal places - .2f ensures exactly 2 digits after decimal (for currency) - Prevents output like 3.3333333 or 10.1

Line 9: print(f"Final price: ${total - discount:.2f}") - - is subtraction operator - total - discount is calculated inside the f-string placeholder - Result is formatted to 2 decimal places - Both operations happen: subtraction, then formatting

Line 11: discount = total * 0.10 - Only executes if total < 100 (first condition False) - 0.10 represents 10% - Variable discount is reassigned with new value

Line 15: print(f"No discount. Total: ${total:.2f}") - For totals under $50 - Still formats to 2 decimal places for consistent currency display