如何退出while循环

时间:2020-08-20 13:04:05

标签: python

因此,基本上,当用户输入“ n”时,我需要它停止并且不要求输入y或n,但是我似乎无法使它出现,有什么帮助吗?

decider = input('Would you like to play the game? [y/n]? ')

while decider != 'y' :
    if decider == 'n' :
        print('Another time perhaps')
    else :
        print('Please enter either \'y\' or \'n\' ')

    decider = input('Would you like to play the game? [y/n]? ')

我也知道您可以使用退出或中断,但在我不允许的锻炼中

3 个答案:

答案 0 :(得分:1)

您需要在检查输入之前和while循环再次检查条件之前询问用户。另外,只要输入不是'n',就需要循环

decider = ''
while decider != 'n' and decide != 'y' :
    decider = input('Would you like to play the game? [y/n]? ')
    if decider == 'n' :
        print('Another time perhaps')
        break
    elif decider == 'y':
        print('Play again!')
        * insert restart code here*
    else :
        print('Please enter either \'y\' or \'n\' ')

答案 1 :(得分:0)

您可以解决该问题,在他插入n时,在ald更改它的同时添加其他字符串。我在下面提供了您和示例。

import sys

decider = input('Would you like to play the game? [y/n]? ')

while decider != 'y':
    if decider == 'n' :
        print('Another time perhaps')
        sys.exit()
    else :
        print('Please enter either \'y\' or \'n\' ')
        decider = input('Would you like to play the game? [y/n]? ')

好吧,我很严格,我编辑代码以不再回答问题

答案 2 :(得分:0)

尝试一下:

run = True
while run:
    decider = input(•••)
    if decider == "n":
        print(•••)
        run = False
    if decider == "y":
        print(•••)
    else:
        print("Please write either y or n")