首页 > 解决方案 > Python打破了一个while循环

问题描述

我对 Python 和这个网站有点陌生。我需要有关我的代码的任何帮助。当用户输入一个值但我遇到问题时,我试图打破循环。我正在为我的学校做一个聊天机器人项目。

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()

标签: pythonjupyter-notebookjupyter

解决方案


如果您正在寻找任何输入,那么您将不需要 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()

或者,如果您想等待特定值,则需要设置一个条件来中断循环。

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"

或者

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

推荐阅读