gpt4 book ai didi

python ,重复random.randint?

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:02 24 4
gpt4 key购买 nike

我是 python 的新手,我想知道如何使代码重复 random.randint 部分 100 次。

#head's or tail's

print("you filp a coin it lands on...")

import random

heads = 0
tails = 0


head_tail =random.randint(1, 2,)

if head_tail == 1:
print("\nThe coin landed on heads")
else:
print("\nThe coin landed on tails")

if head_tail == 1:
heads += 1
else:
tails += 1

flip = 0
while True :
flip +=1
if flip > 100:
break



print("""\nThe coin has been fliped 100 times
it landed on heads""", heads, """times and tails""", tails,
"""times""")

input("Press the enter key to exit")

最佳答案

您可以通过列表理解在一行中完成所有操作:

flips = [random.randint(1, 2) for i in range(100)]

然后像这样计算正面/反面的数量:

heads = flips.count(1)
tails = flips.count(2)

或者更好的是:

num_flips = 100
flips = [random.randint(0, 1) for _ in xrange(num_flips)]
heads = sum(flips)
tails = num_flips - heads

关于 python ,重复random.randint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10707182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com