[英]Can I use an if statement to break a while loop in Python
基本上我想要的是讓程序運行並從頭開始,直到鍵入命令為止。 我有重復部分,但我無法中斷循環。 我試圖使用if語句獲取輸入並使用它來打破循環。 我已經在教程中看到了它的完成,但是我無法讓它對我有用。 我知道break語句將退出循環,我想知道是否可以在if語句中使用break語句,如下所示:
while True:
i == input('Type a letter:') #They type a letter
if i == quit: #If they type "quit" this executes
print('Goodbye') #The program says goodbye
break #Ends the loop
else:
print("Your letter is", i) #If they type anything else, it gets printed
有了這個對我來說,它只是打印:
Type a letter: quit
Your letter is quit
Goodbye
Type a letter:
如果我鍵入它,則不會中斷循環。 如果不可能的話,有人輸入“ quit”之類的代碼結束循環嗎? 任何幫助表示贊賞。
您需要將i
設置為單個等號(這可能是您帖子中的錯字)。
i = input('Type a letter:')
您還需要在引號中加上quit
使其成為字符串。 有了它,就可以將用戶的輸入與內置的quit
函數進行比較 ,因此它們永遠不會相等。
if i == 'quit':
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.