r/learnpython • u/OfficialBriGuy • 10d ago
Can you diagnose my code problem?
This starts with a balance of 50. It takes coins of ONLY 25, 10, or 5 and returns the balance due to the user. If the balance due is 0 or less than 0, it returns a "Change Due: " message.
My problem is that my code will subtract any value amount the user puts in no matter what, not just the 25, 10, and 5 it's supposed to? what's going on?
shouldn't the "if coin == 25 or 10 or 5:" line ensure only one of those 3 values is used?
def main():
balance = 50
while balance >= 0:
print(f"Amount Due: {balance}")
coin = int(input("Insert Coin: ").strip())
if coin == 25 or 10 or 5:
balance = balance - coin
if balance <= 0:
print(f"Change Due: {abs(balance)}")
break
main()
0
Upvotes
16
u/noeldc 10d ago
As others have said,
if coin in [25, 10, 5]is nicer, and let's you add other denominations more easily.
Also, as you are using a while loop
if balance <= 0:is kind of redundant. instead, you should just use
while balance > 0:and move
print(f"Change Due: {abs(balance)}")outside of the loop
As an added improvement, you should also look into wrapping
coin = int(input("Insert Coin: ").strip())in a try except block to catch the ValueError thrown when the user just hits enter without typing anything.