在不中断的情况下要求特定的输入

时间:2019-06-06 17:30:35

标签: python loops input

我正在创建骰子扑克游戏,试图在继续游戏之前先询问用户是否愿意玩,然后在每次游戏后询问玩家是否愿意再次玩游戏。

我不确定如何允许输入除Y和N之外的其他错误内容,以便告诉用户输入正确的答案,然后循环输入直到输入中的任意一个为止。我不允许休息。

play = True
s = input("Would you like to play dice poker [y|n]? ")
if s == "y":
    play = True
elif s == "n":
    play = False
else:
    print("Please enter y or n")

while play:

从这里开始是我的游戏代码

以下各节在每局比赛结束时重复

  again=str(input('Play again [y|n]? '))

    if again == "n":
        play = False
    if again == "y":
        play = True
    else:
        print('Please enter y or n')

1 个答案:

答案 0 :(得分:2)

将您的输入包装在评估用户输入的函数中,如果无效,请根据需要递归调用。示例:

def keep_playing():
    valid = 'ny'
    again=str(input('Play again [y|n]? '))
    a = again.lower().strip()  # allow for upper-case input or even whole words like 'Yes' or 'no'
    a = a[0] if a else ''
    if a and a in valid:
        # take advantage of the truthiness of the index: 
        # 0 is Falsy, 1 is Truthy
        return valid.index(a)
    # Otherwise, inform the player of their mistake
    print(f'{again} is not a valid response. Please enter either [y|n].')
    # Prompt again, recursively
    return keep_playing()

while keep_playing():
      print('\tstill playing...')

enter image description here