简体   繁体   中英

My while loop is keeps looping. What am I doing wrong?

In this the total amount is the amount the user need to pay. If user pay lesser than the total amount the system needs to subtract the payment and show their balance and keep on looping until the payment is completed. But, when I run my codes its keep on looping while showing the balance.

print ("Your total amount is:", total_amount)
print ("")

payment = int(input("Please insert your payment: "))

count = 0
    
while payment != total_amount:
    count = total_amount - payment
    print ("Your balance:", count)
    payment = int(input("Please insert your payment: "))

if payment == total_amount:
    print ("Successful")

does the program outputs "Successful" if the user inputs the total amount on the first input?

if the user doesnt input the total amount on the first input, what could happen is that the variable named payment will never be equal to the total payment, but the count will eventually reach the total amount yes, but the while loop does not has variable count working is logic statement, it uses payment as the variable for its logic. if someones buys a something from a store, and the total is 5 dollars,, and the buyer has 1 dollar bills, the buyer will first put one dollar on the counter, then the other 1, and so on... but the buyer will not put 1 dollar on the counter, and then 5 dollars on the counter, because that would be 6 dollars

You are not updating either payment or total_amount correctly in the loop. I believe this should work.

payment = int(input("Please insert your payment: "))

while payment <= total_amount:
    diff = total_amount - payment
    print("Your balance:", diff)
    payment += int(input("Please insert your payment: "))

if payment == total_amount:
    print("Successful")

Based on your code, only if I pay the correct amount in one go, should I successfully pay. Of course this is wrong. I have modified and added some details to your code like this:

print("Your total amount is: $%.2f \n" % (total_amount)) 
count = 0

while count < total_amount:
    payment = int(input("Please insert your payment: $"))
    count += payment
    print ("Your balance: $%.2f" % (total_amount - count))

print("Successful")
if count > total:
    print("Your change is $%.2f" % (count - total))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM