Objective
Develop a Python program to give change for a purchase, using the largest possible coins (or bills). Suppose we have an unlimited amount of coins (or bills) of 100, 50, 20, 10, 5, 2, and 1, and there are no decimals. Therefore, the execution could be something like this:
Price? 44
Paid? 100
Your change is 56: 50 5 1
Price? 1
Paid? 100
Your change is 99: 50 20 20 5 2 2
Example Python Exercise
Show Python Code
# Ask for the price and the amount paid
price = int(input("Price? "))
paid = int(input("Paid? "))
# Calculate the change
change = paid - price
denominations = [100, 50, 20, 10, 5, 2, 1]
change_list = []
# Loop through the denominations and calculate the necessary coins/bills
for denomination in denominations:
while change >= denomination:
change -= denomination
change_list.append(denomination)
# Print the result
print(f"Your change is {paid - price}: {' '.join(map(str, change_list))}")
Output
Case 1:
Price? 44
Paid? 100
Your change is 56: 50 5 1
Case 2:
Price? 1
Paid? 100
Your change is 99: 50 20 20 5 2 2
Share this Python Exercise