【发布时间】:2021-02-23 13:17:38
【问题描述】:
所以,我正在学习 Python 中的随机化,并想通过制作一种“骰子模拟器”程序来测试我的知识,该程序将四个“骰子”投掷 1000 次;然后计算四个骰子的总和等于或大于 21 的次数。这是我到目前为止所得到的:
import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
dice4 = random.randint(1,6)
sum = dice1 + dice2 + dice3 + dice4
n = 0 # the amount of times the sum of the score was 21 or higher
for i in range(1000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
dice4 = random.randint(1,6)
for sum >= 21:
n = n + 1
print("You got 21 or higher", n, "times.")
但是,程序的结果窗口只显示“你得到 21 或更高的 0 次。” 或 “你得到 21 或更高的 1000 次。”。所以,我想我的问题是:如何修复代码,以便计算 1000 次“掷骰子”中得分总和为 21 或更高的次数,在结果窗口中打印所述次数,我的代码中的哪一行需要修复(又名:哪里出错了)?提前致谢!
【问题讨论】:
-
你确定你写的是
for sum >= 21:吗?这不是有效的 Python 语法。for应该是if。另一个问题是您忘记在for循环内更新变量sum,因此它保持其初始值(第一次滚动的四个骰子的总和)。 -
您没有在 for 循环中更新 sum,顺便说一句,避免使用此名称,因为它会影响内置 sum
标签: python for-loop while-loop probability dice