I am building a python vending machine program where you input price and get change due. Ive got the price working fine and the change for the most part, but Im trying to figure out how to give exact change. Im using dollars, quarters, dimes, nickels and pennies. I am trying to stop it from giving incorrect change when I put in a number that is not even in quarters. For example if I put in 5 dollars for my bill and 260 for the price (im only up to dimes at this point) It tells me that I will get 2 dollars, 1 quarter, and 4 dimes. I still need to add nickels and pennies, but how do I stop it from doing this. I know there are a whole bunch of different ways to give 40 cents change back, but I need it to be precise.

Recommended Answers

All 2 Replies

Typically you'd want to give as few of each unit of change as possible. Start with a list of denominations from largest to smallest and cycle through them in turn, extracting as many of each denomination as possible. Stop when there is no more change to give.

For extra credit you can use a dictionary to include the descriptive unit words (like "quarters", "nickels", etc.).

Your question made me think of a rather awful vending machine experience. The sign on the machine read:

Correct change only.

Can of soda is 70 cents, put in a dollar bill, it keeps the change.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.