1

我是 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")
4

5 回答 5

5

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

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
于 2012-05-22T17:49:37.267 回答
3

首先,我将该while循环替换为:

for flip in xrange(100):
  ...

其次,要进行 100 次随机试验,请将randint()调用以及您想要执行 100 次的所有其他内容移动到循环体内:

for flip in xrange(100):
  head_tail = random.randint(1, 2)
  ...

最后,这是将如何做整个事情:

heads = sum(random.randint(0, 1) for flip in xrange(100))
tails = 100 - heads
于 2012-05-22T17:44:46.703 回答
2

您将使用range(100), 因为您在 Python3.x 上,它创建了一个从 0 到 99(100 个项目)的列表。它看起来像这样:

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

import random

heads = 0
tails = 0


for i in xrange(100):
    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    


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")
于 2012-05-22T17:50:38.890 回答
1
for flip in range(100):
    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
于 2012-05-22T17:47:57.530 回答
0

我是 Python 新手,通常是编程新手,但我基于 1 天的编程实践创建了自己的代码。硬币翻转编码练习是我现在学习的书中的第一个练习。我试图在互联网上找到解决方案,我找到了这个主题。

我知道要使用本主题中的任何代码,因为我不熟悉以前答案中使用的一些函数。

对于处于类似情况的任何人:请随时使用我的代码。

import random

attempts_no = 0
heads = 0
tails = 0

input("Tap any key to flip the coin 100 times")


while attempts_no != 100:
 number = random.randint(1, 2)
 attempts_no +=1
 print(number)
 if number == 1:
    heads +=1
 elif number ==2:
    tails +=1

print("The coin landed on heads", heads, "times")
print("The coin landed on heads", tails, "times")
于 2015-04-12T12:32:30.607 回答