我是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")
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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")
答案 3 :(得分: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
答案 4 :(得分: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")