Python function to calculate change

Python function to calculate change

 

Project Instructions

Write a Python function to calculate change when customers pay in cash at the checkout. The function will take the price of the product and the note given to pay. The function will return the change broken down in coins and notes.

Given the list of EUR notes and coins:
notes = [5, 10, 20, 50, 100]

coins = [0.01, 0.05, 0.1, 0.5, 1, 2]

For example, if you enter a note of 20 to pay 12.75 EUR, it should return:
2 coins of 0.1
1 coin of 0.05
1 coin of 2
1 note of 5

It is a real Python challenge since you will have to create a program that simulates the software of the cash registers of any retailer. It is a good Python exercise to apply logic and practice loops and conditional statements.

Steps

  1. Start by defining a function called "calculate_change" that takes two arguments: "price" and “note".
  2. Inside the function, calculate the total change owed by subtracting the price from the note. Assign this value to a variable called "change".
  3. Create a list called "change_breakdown" to store the breakdown of coins and notes.
  4. Use the modulo operator (%) and integer division (//) to calculate the number of each coin and note denomination needed.
  5. Append the calculated values to the "change_breakdown" list in the order of the largest denomination to the smallest.
  6. Finally, return the "change_breakdown" list.

Python Project Solution

# Lists of available Euro notes and coins
NOTES = [100, 50, 20, 10, 5]
COINS = [2, 1, 0.5, 0.1, 0.05, 0.01]

def get_float_input(prompt):
    """Get a valid float input from the user."""
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please enter a valid number.")

def get_int_input(prompt):
    """Get a valid integer input from the user."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a valid integer.")

def calculate_change(price, payment):
    """Calculate and return the change breakdown."""
    if payment < price: return "Error: Insufficient payment." change = round(payment - price, 2) if change == 0: return "No change due." breakdown = [] for denomination in NOTES + COINS: count = int(change // denomination) if count > 0:
            change = round(change - count * denomination, 2)
            item_type = "note" if denomination >= 5 else "coin"
            breakdown.append(f"{count} {item_type}(s) of {denomination}")

    return "\n".join(breakdown)

def main():
    print("Welcome to the Change Calculator")

    # Get user inputs
    price = get_float_input("Enter the price of the product in Euros: ")
    payment = get_int_input("Enter the denomination of the note used for payment: ")

    # Validate the payment denomination
    if payment not in NOTES:
        print("Error: Invalid note denomination. Please use 5, 10, 20, 50, or 100 Euro notes.")
        return

    # Calculate and display the change
    result = calculate_change(price, payment)
    print("\nChange Breakdown:")
    print(result)

if __name__ == "__main__":
    main()

Expected Output

## We pay something that costs 12.75 EUR with a note of 20 Eur
price = 12.75
note = 20

change_breakdown = calculate_change(price, note)
for item, count in change_breakdown.items():
    print(f"{count} {'notes' if isinstance(item, int) else 'coins'} of {item}")

## Output
1 notes of 5
1 coins of 0.1
1 coins of 0.05
1 coins of 2

 

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart