簡體   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