[英]Can I use an if statement to break a while loop in Python
Basically what I want is to have the program run and start back at the beginning until a command is typed. 基本上我想要的是让程序运行并从头开始,直到键入命令为止。 I have the repeat part working, but I can't get the loop to break when I want it to. 我有重复部分,但我无法中断循环。 I was trying to use an if statement to take the input and use it to break the loop. 我试图使用if语句获取输入并使用它来打破循环。 I've seen it done in tutorials, but I can't get it to work for me. 我已经在教程中看到了它的完成,但是我无法让它对我有用。 I understand the break statement is to exit a loop, I'm wondering if it is possible to use the break statement in an if statement like so: 我知道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
With this for me it just prints,: 有了这个对我来说,它只是打印:
Type a letter: quit
Your letter is quit
Goodbye
Type a letter:
if I type it, not breaking the loop. 如果我键入它,则不会中断循环。 If it's not possible, does anybody have another way that I could get the same result, having the loop end when I type something like "quit"? 如果不可能的话,有人输入“ quit”之类的代码结束循环吗? Any help is appreciated. 任何帮助表示赞赏。
You need to set i
with a single equals sign (this may have been a typo in your post). 您需要将i
设置为单个等号(这可能是您帖子中的错字)。
i = input('Type a letter:')
You also need to put quit
in quotes to make it a string. 您还需要在引号中加上quit
使其成为字符串。 As you have it, you're comparing the user's input with the builtin quit
function , so they'll never be equal. 有了它,就可以将用户的输入与内置的quit
函数进行比较 ,因此它们永远不会相等。
if i == 'quit':
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.