繁体   English   中英

while循环还是for循环? (蟒蛇)

[英]While loop or for loop? (python)

我对编程非常陌生,而我刚开始使用python。 我找到了一些练习来进行一些练习,但我被困在while和for循环中。

我想设计一个程序,要求捐赠,并一直要求捐赠,直到捐赠了至少50欧元。 当达到此最低或更高要求时,我想停止该程序,并感谢人们的捐款。

我的代码如下所示:

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"

但这根本不起作用,我觉得我在这里完全错过了一些东西。

谁能帮助我编写有效的代码?

while循环中的if条件根本不需要。 循环将继续进行,直到donation >= 50这样您就可以在循环后打印消息了:

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"

代码的实际问题与循环无关。 正如David所指出的,您可以写得更好,但是您所拥有的却行之有效 ,只是有些冗长。

问题在于您正在将字符串与数字进行比较。 raw_input始终返回一个字符串。 而且,字符串不能少于任何数字。 因此, donation < 50永远是不正确的。

您需要将其转换为一个int (或floatDecimal或其他任何适当类型的数字):

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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