簡體   English   中英

無法使FOR循環正常工作

[英]Can't get FOR loop to work

下面,我插入了一些代碼,這些代碼顯然對大多數Python新手來說都是錯誤的,除了最新手。

請問人們是否願意建議新手對代碼進行一些改進? 例如邏輯變量名稱,添加注釋等。

根據問題中的要求,也將對代碼中的錯誤進行更正。


我在使下面的循環正常工作時遇到問題。 有人對什么地方有任何建議嗎? 此刻,我被問到問題,然后代碼顯示錯誤。

應該發生的是,我被問到一個問題,然后有3次機會正確回答。

a = input("What is the opposite to night?")

for xx in range(0,3)
    if a == Night:
    print("That's right! Well done")
    else:
    print("Sorry, try again")

請參見以下更正:

a = input("What is the opposite to night?")

for x in range(0,3): # must have colons at the end of for statement
    if a.lower() == "night":   # we should accept all cases
      print("That's right! Well done") # indentation required in if statement
    else:
      print("Sorry, try again") # indentation required also 

我認為,問對的是更有價值的:

  • input(..)在循環中被調用一次
  • for循環的末尾沒有冒號
  • 您應該使用字符串來比較答案,因此"Night"
  • 該字符串實際上應"day"進行比較,因為這是正確的答案;
  • 答案是更好地測試,不區分大小寫
  • 如果這是最后一次機會 ,則不應說"try again"
  • 它是(榮譽給@TemporalWolf)“ 相對”;
  • 如果答案是正確的 ,那就沒有break ;
  • 縮進是錯誤的

因此,解決方法是:

for xx in range(0,3): # colon
    a = input("What is the opposite of night?") # input in the loop
    if a.lower() != "day": # comparing against "day" (string)
        if xx < 2: #only print try again if it is not the last chance
            print("Sorry, try again") #indentation
        else:
            print("Too bad, well goodbye.")
    else:
        print("That's right! Well done") # indentation
        break # break if correct

附加建議:您可以使用range(3)代替較短的range(0,3)

for _ in range(3): print(["Sorry, try again", "That's right! Well done"]
[input("What is the opposite to night?").lower()=='day'])

並非所有答案都會有幫助,即使它們會產生“正確”的答案

如果您從StackOverflow中“借用”代碼,您可能會被發現。

for xx in range(0,3)

應該

for x in range(0,3):

並且可以通過以下方式進行優化(盡管在很小的范圍內非常小)

for x in xrange(3)

最后,Night需要用引號引起來,以便:

if a == "Night"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM