Vending Machine Program (calculate The Amount That Has To Inserted,etc.)
Solution 1:
Your specific error stems from the fact that you do not deal correctly with the case where you exactly reach the total - you overshoot, then have to give change. However, your code is very long and complex and it is difficult to figure out exactly what it is doing at each stage.
A few general coding suggestions:
eval
is a bad idea; it is better to useint(input(...))
, which will also make a fuss for you if the user doesn't enter an integer.- Your outer
for
loop should really be awhile
loop, rather than guessing a maximum number of iterations (which all run, even after you've made change!) - You have a lot of repeated code and hard-coded values; whenever you write similar things repeatedly consider splitting them out into a function with arguments, or some kind of loop.
Also, reading your description, specifically:
Given the cost, the user should first be prompted to add more money until the cost is met/exceeded by the payment.
I think you are supposed to be allowing the user to input
coins rather than guessing what they will enter.
Here is one possible implementation:
defvend():
"""Simulate a vending machine, taking user input and returning remainder."""
total = int(input("Enter the cost (in cents): "))
inserted = 0while inserted < total:
inserted += int(input("Deposit a coin or note (in cents): "))
if inserted > total:
return make_change(inserted - total)
defmake_change(remainder):
"""Calculate the coins required to make change equal to amount."""
coins = ["$1", "25c", "10c", "5c", "1c"]
amounts = [int(coin[:-1]) if coin.endswith("c")
else100 * int(coin[1:])
for coin in coins]
counts = [0for _ in coins]
for index, amount inenumerate(amounts):
counts[index] = remainder // amount
remainder %= amount
return", ".join("{0} x {1}".format(count, coin)
for count, coin inzip(counts, coins)
if count)
Note the division of responsibility between the two functions, to make it easier to test each one separately, and the appropriate use of for
and while
loops to minimise repetition. Also, I have made amounts
and paid
in make_change
depend on coins
, so you only have to change in one place to add new coins.
Example usage:
>>> vend()
Enter the cost(in cents): 135
Deposit a coin or note(in cents): 100
Deposit a coin or note(in cents): 50'1 x 10c, 1 x 5c'
Post a Comment for "Vending Machine Program (calculate The Amount That Has To Inserted,etc.)"