0

Hello everyone so I started working on a dice rolling game that rolls the dice then displays the value and asks if the user would like to re-roll. I know how to do all that but I wanted to put in a part that would loop if the user put in a value that was not Y(Yes) or N(No). So I created another while statement to accomplish this. If you input an invalid response the program asks you to type Y or N. Then if you type an invalid response again it keeps asking until the expected value is entered. Here is the code and I'll highlight the part where I don't understand. I commented why I think it works but I'm not sure. If someone could explain why it works I appreciate it thanks a lot!

import random

value = random.randint(1, 2)

run = True

while run:

    print("You roll a six sided dice \n")

    print("Your dice landed on "+str(value) + "\n")

    answer = input("Do you want to play again? (Y or N) \n")

    if answer == "Y":

        continue

    if answer == "N":

        print("Thanks for playing \n")

        exit()

    # after you type an invalid response it's stored in variable answer
    # the program then goes to answer2 input which asks please enter Y or N
    # if the program then detects an invalid answer it goes back to the top
    # of the while statement and uses answer ones response which is still
    # an invalid response???? I'm guessing since answer is always invalid and the
    # decisions only two options that are yes or no it goes back to the top of the 2nd while loop
    # Not sure tho.

    # 2nd while loop
    while answer != "Y" or "N":

        answer2 = input("Please enter Y or N \n")

        while answer2 == "Y":

            print("You roll a six sided dice \n")

            print("The dice landed on " + str(value) + "\n")

            answer2 = input("Do you want to play again \n")

            continue

        if answer2 == "N":

            print("THanks for playing")

            exit()

I've commented out why I think it works but

1 Answers1

0
import random

value = random.randint(1, 2)

def getans():

    while True:
        answer = raw_input("Do you want to play again? (Y or N) \n")

        if answer == "Y":

            return True

        elif answer == "N":

            return False

        else:
            print ("Please enter Y or N \n")
            continue


while True:

    print("You roll a six sided dice \n")

    print("Your dice landed on "+str(value) + "\n")

    answer = getans()

    if answer == True:

        continue

    elif answer == False:

        print("Thanks for playing \n")
        exit()
    else:

        print ("this will never run")
AshkarMHM
  • 1
  • 3