Home > database >  Repeating code if not more than 50 value is given or more
Repeating code if not more than 50 value is given or more

Time:06-14

I'm currently taking Harvard classes on CS50 online, as well as their assignments are given. I'm doing the vending machine at the moment, I'm having trouble because every time I run the code and give a value number of less than 50 it repeats itself in a loop.

print("amount due: 50")


run = True
while True:

    coin = int(input(f"Insert coin: "))
    if coin <= 50:
        sum = 50 - coin
        print(f"amount due: {sum}")
        if sum == 0:
            print(f"change owe: {sum} ")
            break
    elif coin > 50:
        sum = -50   coin
        print(f"change owed: {sum}")
        break

CodePudding user response:

At least one problem is here.

If coin is less or equal to 50 you break the loop if sum is zero. Think what happens if I insert first 10 and then 45.

Another, and even bigger problem is that you always reduce from 50, not from due amount.

Third thing, you don't use your run variable. But you'd need due amount variable to make this work.

Since this is a school assigment, I won't provide fixed code for you. You learn more if you do that yourself.

CodePudding user response:

if sum == 0 will make you break if and only if all coins at some point sum up to exactly 50. If not, sum will go below 0 forever.

Change it to if sum <= 0.

Also, read about breakpoints and debugging in the code editor you are using. Shouldn't take much time to learn, but will help a lot with this kind of problems in the future.

  • Related