如何使用用户输入中断while循环

我发现很难在用户输入“ N”时中断while循环,而仅接受“ Y”。输入“ N”仍将激活第二个while循环。

如何编写这样的代码:一旦用户输入IN,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()
点赞
评论
神经
神经

Try to add break if the received input equals to "N":

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

    choice = input('Would you like to continue? (y/n): ').upper()
    if choice == "N":
        break

    while (choice != 'Y') and (choice != 'N'):
        choice = input('Please choose Y for yes, or N for no!: ').upper()
点赞
评论