David Caldwell David Caldwell - 2 months ago 27
Python Question

Adding "Invalid Entry" To Python Dice Roller

I have a Python dice rolling simulator:

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


If you input anything other than "y" or "n" it will roll again. I would like to make it so that it will say something like "invalid entry" instead of rolling again. How could I change this to do so? Thank you.

Answer

You can validate the answer and ask again if it is invalid like

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
Comments