我正在用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 次”。或“你有 1000 次得到 21 或更高。”当我尝试运行它时。如何编写代码,以便计算 1000 次掷骰子中得分总和为 21 或更高的次数,并在终端中打印次数?预先感谢您!
您应该更新
sum
循环内的变量 for
。否则,它保持其初始值,即第一掷中四个骰子的总和。
请注意,它们是一个名为
sum
的 Python 内置函数,为变量使用内置名称是非常糟糕的做法。下面,我将变量重命名为 sumOfDice
。
import random
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)
sumOfDice = dice1 + dice2 + dice3 + dice4
if sumOfDice >= 21:
n = n + 1
print("You got 21 or higher", n, "times.")
当您开始使用名称中带有数字的变量时,您应该问自己:我真的需要四个命名变量作为骰子吗?使用一个列表来保存四个值不是更容易吗?如果
dice
是一个列表,那么您可以访问 dice[0]
、dice[1]
等各个值。但您也可以使用循环列表推导式和其他很酷的 Python 功能来操作列表。你甚至可以调用Python内置函数sum
来获取列表的总和!!
import random
n = 0
for i in range(1000):
dice = [random.randint(1,6) for _ in range(4)]
if sum(dice) >= 21:
n = n + 1
print("You got 21 or higher, {} times.".format(n))
我解决了这个问题。你可以试试这个吗
import random
n = 0
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)
sum = dice1 + dice2 + dice3 + dice4
if sum >= 21:
n = n + 1
print("You got 21 or higher", n, "times.")
您需要计算 for 循环内骰子的总和。
在您的示例中,总和始终等于前 4 次调用
random.randint
中生成的随机数之和,但您应该每次重新计算总和。
此外,在有
for sum >= 21
的地方,应将 for
替换为 if
。 for
用于重复,if
用于条件执行。
您不需要定义骰子,每个
random.randint(1,6)
本身就是一个骰子。
import random
n = 0 # the amount of times the sum of the score was 21 or higher
for i in range(1000):
sum = random.randint(1,6) + random.randint(1,6) + random.randint(1,6) + random.randint(1,6)
if sum >= 21:
n = n+1
print("You got 21 or higher", str(n), "times.")
这是一种Pythonic方式:
dice_sum = [int((x/x)) for x in range(1,1001) if random.randint(1,6) + random.randint(1,6) + random.randint(1,6) + random.randint(1,6) >= 21]
print("You got 21 or higher", str(sum(dice_sum)), "times.")
我所做的就是每次骰子为
>= 21
时获取索引,然后将其除以相同的索引,这样它就将1返回到列表中,然后我得到列表的总和,这就是1有多少次已添加到列表中,即骰子被 >= 21
了多少次。