繁体   English   中英

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

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

当用户输入“N”时,我发现很难打破while循环,它只接受“Y”。 输入“N”仍将激活第二个 while 循环。

我如何编写这样一旦用户输入 N,while 循环就会中断? 先感谢您:)

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

提供的另一个答案很棒,但我想举一个使用“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