如果 roll_more == 'no' 则循环不退出

Loop not exiting if roll_more == 'no'

我尝试制作一个简单的掷骰子程序,我可以将骰子掷到 'roll' 但我无法停止它,它只会在您输入任何内容时保留。我试着添加它,所以如果你说 'no' 或 'n' 它将 return 并像往常一样转到我的其他功能。我说 return 因为继续我的其他代码很重要。谢谢你。

import random
min = 1
def rolling6():
    roll_more = "yes"
    while roll_more == "yes" or roll_more =="y":
        max = 6
        print("Rolling the dices...")
        print("The values are...")
        print(random.randint(min, max))
        print(random.randint(min, max))
        roll = input("Roll the die again? ")

    if roll_more == "no" or roll_more == "n":
        return
    #roll_again = "yes"
    #while roll_again == "yes" or roll_again =="y":
    #   print("Rolling the dices...")
    #   print("The values are...")
    #   print(random.randint(min, 6))
    #   print(random.randint(min, 6))
    #   roll_again = input("Roll the die again? ")

    #if roll_again == "no" or roll_again == "n":
    #   return


x = input("Use six sided die? ") 
while x == "yes" or x =="y":
    rolling6()

您正在写入 roll 而不是 roll_more,因此您总是在检查常量 "yes"。

此外,您的 xroll_more 变量不包含您期望的值。首先,你输入 "yes" 进入循环,因为 rolling6 永远被调用。然后,您进入 rolling6 循环。当您通过输入 "no" 退出时,您退出到外循环,读取 x 仍然具有值 "yes" (因为您从未在任何地方覆盖它),这意味着您没有跳出该循环,而是再次进入 rolling6

您可能想将 roll 更改为 roll_more 并将 while x == "yes" or x =="y": 更改为 if x == "yes" or x =="y":

此外,您的 if roll_more == "no" or roll_more == "n": return 是多余的,因为该语句之后没有代码。