python中的while循环不会停止

2024-01-22

我们正在尝试制作一个Python程序来模拟掷骰子游戏并显示获胜的概率。我已经缩小了 while 循环的答案,正如标题所示,当它到达循环时,它不会退出。据我所知,循环应该退出,但只是返回和无尽的“假”序列。这是带有注释的整个程序的代码,我将在底部键入掷骰子的规则(就我们在程序中使用的规则而言)。

import random
def craps()
    roll = random.randint(1,6) + random.randint(1,6)
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter 
    return 1
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0
    return 0
else:
    roll2 = 0 #initializes roll2 for the while
    while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
        roll2 == random.randint(1,6) + random.randint(1,6) #Rolls the dice
        if (roll2 == roll): #Tests if the player should win
            return 1
        elif (roll2 == 7): #Tests if the player should lose
            return 0

win = 0 #Start the win counter at 0
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played
for i in range (games): 
    win = win + craps() #adds a 1 or a 0 depending on if a game was won

print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning

我们使用的基本规则是:玩家掷 2 个六面骰子,如果初始掷骰子是 7 或 11,则玩家获胜(第 4 行)。如果玩家掷出 2、3 或 12,则玩家输(第 6 行)。如果玩家没有得到,则他们继续掷骰子,直到匹配初始掷骰子或掷出 7。如果他们匹配初始掷骰子,则他们获胜,如果他们得到 7,但输了(第 10-15 行)。我们的程序应该模拟并显示玩家获胜的概率。

这是我第一次使用这个网站,所以如果我将来搞砸了任何事情,请告诉我。感谢您的帮助!


这是一个常见但非常令人沮丧且浪费时间的拼写错误,即使是最优秀的 Python 开发人员也会遇到这种情况。代替roll2 == random.randint(1,6) + random.randint(1,6) with roll2 = random.randint(1,6) + random.randint(1,6).

另外,我认为你需要roll2 != roll and roll2 != 7。从风格的角度来看,最好省略在表达式中评估的语句周围的括号。if or while line.

不过,您的循环中有少量冗余。您检查roll2 being roll or 7在每个循环的顶部和每个循环的末尾。你也可以考虑尝试这个:

while True:
    # do everything in the same way as before

or

while roll2 != roll and roll2 != 7:
    # do stuff with the roll
    roll = random.randint(1,6) + random.randint(1,6)
return 1 if roll2 == roll else return 0 # a "ternary operator" in Python
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中的while循环不会停止 的相关文章