繁体   English   中英

我可以使用if语句中断Python中的while循环吗

[英]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.

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