mercredi 20 mai 2020

I don't understand why this nested while loop works please python

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

Aucun commentaire:

Enregistrer un commentaire