简体   繁体   English

Python 打破 while 循环

[英]Python Breaking a While Loop

I am kinda new to Python and new to this website.我对 Python 有点陌生,对这个网站也是新手。 I would like any assistance with my code.我想要任何有关我的代码的帮助。 I am trying to break the loop when the user inputs a value but I am having trouble with it.当用户输入一个值时,我试图打破循环,但我遇到了问题。 I am doing a chat bot project for my school.我正在为我的学校做一个聊天机器人项目。

while ans:
        user_input = input("How are you?: (or press enter to quit) ")
        user_input = ''.join(ch for ch in user_input if ch not in exclude)
        user_words = user_input.split()

If you're looking for any input then you wouldn't need the while loop, Python will pause the program whilst it waits for a user input.如果您正在寻找任何输入,那么您将不需要 while 循环,Python 将在等待用户输入时暂停程序。

user_input = input("How are you?: (or press enter to quit) ")
user_input = ''.join(ch for ch in user_input if ch not in exclude)
user_words = user_input.split()

Alternatively if you want to wait for a specific value, you would need to set a condition to break the loop.或者,如果您想等待特定值,则需要设置一个条件来中断循环。

ans = True
while ans != "Quit":
    user_input = input("How are you?: (or press enter to quit) ")
    user_input = ''.join(ch for ch in user_input if ch not in exclude)
    user_words = user_input.split()
    if user_input == "Quit":
        ans = "Quit"

or或者

while ans:
    user_input = input("How are you?: (or press enter to quit) ")
    user_input = ''.join(ch for ch in user_input if ch not in exclude)
    user_words = user_input.split()
    if user_input == "Quit":
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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