向Python Dice Roller添加“无效条目”

时间:2016-09-11 04:47:29

标签: python python-3.5

我有一个Python骰子滚动模拟器:

from random import randint

play = True

while play:
    roll = randint(1, 6)
    print(roll)
    answer = input("Roll again? (y/n)")
    print(answer)
    if answer == "y":
        play = True
    elif answer == "n":
        break

如果输入“y”或“n”以外的任何内容,它将再次滚动。我想这样做它会说“无效输入”而不是再次滚动。我怎么能改变这个呢?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以验证答案并再次询问是否无效,如

from random import randint

play = True

while play:
    roll = randint(1, 6)
    print(roll)
    ask = True
    while ask:
        answer = input("Roll again? (y/n)")
        print(answer)
        if (answer != "y") and (answer != "n"):
            print("Invalid input")
        else:
            ask = False
    if answer == "y":
        play = True
    elif answer == "n":
        break