简体   繁体   English

如何使用用户输入打破 while 循环

[英]How do I break the while loop with user input

I'm finding it difficult to break a while loop when a user inputs an 'N', it only accepts a 'Y'.当用户输入“N”时,我发现很难打破while循环,它只接受“Y”。 Inputting an 'N' will still activate the second while loop.输入“N”仍将激活第二个 while 循环。

How do I write such that once user inputs N, the while loop breaks?我如何编写这样一旦用户输入 N,while 循环就会中断? Thank you in advance:)先感谢您:)

choice = 'Y'
while choice == 'Y':

    choice = input('Would you like to continue? (y/n): ').upper()
    # it breaks at this point  

    while (choice != 'Y') or (choice != 'N'):
        choice = input('Please choose Y for yes, or N for no!: ').upper()
choice = 'Y'
while choice == 'Y':
    choice = input('Would you like to continue? (y/n): ').upper()
    while (choice != 'Y') and (choice != 'N'): # and, not or!
        choice = input('Please choose Y for yes, or N for no!: ').upper()

The other answer provided was fantastic but I want to give an example using the "break" statement.提供的另一个答案很棒,但我想举一个使用“break”语句的例子。

  while True:
        user_input = input("Run more y/n?")
        if user_input == 'y':
            print("I'm still running in the loop")
        elif user_input == 'n':
            print("I am no longer running and have broken from the while loop.")
            break
        else:
            print("The input is invalid but I'm still running in the loop. Try again")

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

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