python,重复random.randint吗?

Jac*_*ing 1 python

我是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")
Run Code Online (Sandbox Code Playgroud)

Joe*_*ett 5

您可以使用列表理解功能在一行中完成所有操作:

flips = [random.randint(1, 2) for i in range(100)]
Run Code Online (Sandbox Code Playgroud)

并像这样计算头/尾的数量:

heads = flips.count(1)
tails = flips.count(2)
Run Code Online (Sandbox Code Playgroud)

或者更好:

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