Search code examples
python-3.xdice

Dice Simulator project in Python 3


My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop?


import random

min = 1
max = 6

prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)

while roll_dice:

    if roll_dice == "yes":
        print ("you rolled", random.randint(min, max), random.randint(min, max))
        input(prompt)

    elif roll_dice == "no":
        print ("see you later!")
        break

    else:
        print ("invalid answer")
        break

Solution

  • Instead of just doing:

    input(prompt)
    

    Which does nothing with the given input which means roll_dice will always be equal to yes and you will be stuck in an infinite loop.

    You should use:

    roll_dice = input(prompt)
    

    which sets roll_dice to the new value, and hence lets you exit out of the loop.