简体   繁体   中英

While loop or for loop? (python)

I am very new to programming and I am just starting out with python. I found some exercises to practice a little bit and i got stuck at while and for loops.

I want to design a program that asks for a donation, and keeps asking for this donation until the minimum amount of 50 euro is donated. WHen this minimum or more is reached i want to stop the program and thank people for the donation.

My code looks like this:

donation = raw_input("enter your donation: ")

while donation < 50:
        donation= raw_input("We are sorry that's not enough, enter again: ")
        if donation >= 50 print "thank you for the donation"

but this doesn't work at all, i feel like i am missing something completely here.

Who could help me write a working code?

The if condition within the while loop shouldn't be necessary at all. The loop will continue until donation >= 50 so you should just be able to print the message after the loop:

donation = raw_input("enter your donation: ")

while donation < 50:
        donation= raw_input("We are sorry that's not enough, enter again: ")

print "thank you for the donation"

The actual problem with your code has nothing to do with the loop. As David pointed out, you can write that better, but what you have works , it's just a bit verbose.

The problem is that you're comparing strings to numbers. raw_input always returns a string. And no string is ever less than any number. So, donation < 50 will never be true.

What you need is to turn it into an int (or float or Decimal or some other kind of number, whatever's appropriate):

donation = int(raw_input("enter your donation: "))

while donation < 50:
    donation = int(raw_input("We are sorry that's not enough, enter again: "))
    if donation >= 50: print "thank you for the donation"
if donation >= 50: print "thank you for the donation"

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