【问题标题】:I don't understand why this nested while loop works please python [duplicate]我不明白为什么这个嵌套的while循环可以工作python [重复]
【发布时间】:2020-05-21 02:20:52
【问题描述】:

大家好,所以我开始制作一个掷骰子游戏,掷骰子然后显示值并询问用户是否想重新掷骰子。我知道如何做所有这些,但我想放入一个如果用户输入的值不是 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()

我已经注释掉了为什么我认为它有效,但是

【问题讨论】:

    标签: python loops if-statement while-loop nested


    【解决方案1】:
    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")
    

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 2018-08-16
      • 2020-02-10
      • 2016-01-24
      • 2022-12-10
      • 2019-07-03
      相关资源
      最近更新 更多