user17144102
user17144102

Reputation:

Finding change for a number

I'm a beginner and I was given a project. What I have written down right now works for every number besides the one I need 83 where it says I don't need nickel when I do. I tried doing different operations but that messes the math up with the other numbers. If you could help that would be great.

total = int(input("Enter change [0...99]: "))
half = total // 50
quarter = total % 50 // 25
dimes = total % 25 // 10
nickels = total % 10 // 5
pennies = total % 5 // 1

print(half, "half (ves)")
print(quarter, "Quarter (s)")
print(dimes, "Dime (s)")
print(nickels, "Nickel (s)")
print(pennies, "penny (s)")

Upvotes: 1

Views: 73

Answers (1)

user2390182
user2390182

Reputation: 73470

You should update total after each coin:

half = total // 50
total = total % 50
# ...

This is because not all the coins are dividers of all the preceding coins. E.g. removing 25 from an amount changes its divisibility by 10, so total % 10 is not the same amount as remainder_after_dimes (if you had an odd number of quarters).

This could be done in a single step, using divmod:

half, total = divmod(total, 50)
quarter, total = divmod(total, 25)
dimes, total = divmod(total, 10)
nickels, total = divmod(total, 5)
pennies, total = divmod(total, 1)

Upvotes: 3

Related Questions