首页 > 解决方案 > 我不明白为什么这个嵌套的while循环可以工作请python

问题描述

大家好,所以我开始制作一个掷骰子游戏,掷骰子然后显示值并询问用户是否想重新掷骰子。我知道如何做所有这些,但如果用户输入的值不是 Y(Yes) 或 N(No),我想放入一个循环的部分。所以我创建了另一个while语句来完成这个。如果您输入无效响应,程序会要求您输入 Y 或 N。然后,如果您再次输入无效响应,它会继续询问,直到输入预期值。这是代码,我将突出显示我不明白的部分。我评论了为什么我认为它有效,但我不确定。如果有人能解释它为什么起作用,我将不胜感激!

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()

我已经评论了为什么我认为它有效但是

标签: pythonloopsif-statementwhile-loopnested

解决方案


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")

推荐阅读