[英]Why is my simple else statement not working correctly in my while loop?
我是一個菜鳥,可能很愚蠢,但非常感謝您的幫助。 我想知道為什么代碼在執行“else”語句時完成,我希望它繼續“while”循環。
import random
happy == "no"
while happy == "no":
stat = random.randint(1,50)
print (stat)
happy = input("Are you happy with this?" )
if happy == "yes":
print("Okay moving on. ")
break
else:
print("Please enter a valid answer. ")
您的else
應該與if
處於相同的縮進級別,並且您試圖在第二行中進行比較( ==
),而不是定義變量happy
to be no
(with =
)。 這是固定代碼,我可以在 Python 3.7.4 中驗證它是否適合我:
import random
happy = "no"
while happy == "no":
stat = random.randint(1,50)
print (stat)
happy = input("Are you happy with this?" )
if happy == "yes":
print("Okay moving on. ")
break
else:
print("Please enter a valid answer. ")
while
中的else
子句用於特定目的- 即使對於非初學者 Python 開發人員(更不用說新手)也有些違反直覺。 您“偶然”偶然發現了這個構造,這就是為什么您的代碼沒有拋出SyntaxError
並且可能在調試過程中誤導了您。
答案是因為你的縮進。 縮進在 Python 中非常重要。
您想要做的是將else
語句移動到與if
相同的縮進級別,這樣邏輯就說:
Check if this condition is true, otherwise (else), do this
一個簡單的縮進應該可以解決您的問題。
import random
happy = "no"
while happy == "no":
stat = random.randint(1,50)
print (stat)
happy = input("Are you happy with this?" )
if happy == "yes":
print("Okay moving on. ")
break
else:
print("Please enter a valid answer. ")
我的朋友通過更改我的 While 循環來修復代碼。 他將“while happy ==”no”改為“while True”。他解釋說之前不起作用的原因是因為“else”語句仍在更改“happy”變量,因為我要求用戶在前面的“if”語句中為它輸入一個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.