简体   繁体   中英

Python Breaking a While Loop

I am kinda new to Python and new to this website. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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