抛硬币问题的Python代码
我一直在用 python 编写一个程序,模拟 100 次抛硬币并给出抛硬币的总数。问题是我还想打印正面和反面的总数。
这是我的代码:
import random
tries = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print(total)
我一直在绞尽脑汁寻找解决方案,但到目前为止我一无所获。除了抛掷总数之外,有什么方法可以打印正面和反面的数量吗?
I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.
Here's my code:
import random
tries = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print(total)
I've been racking my brain for a solution and so far I have nothing. Is there any way to get the number of heads and tails printed in addition to the total number of tosses?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
您有一个用于尝试次数的变量,它允许您在最后打印该变量,因此只需对正面和反面的数量使用相同的方法即可。在循环外创建一个
heads
和tails
变量,在相关的if coin == X
块内递增,然后在最后打印结果。You have a variable for the number of tries, which allows you to print that at the end, so just use the same approach for the number of heads and tails. Create a
heads
andtails
variable outside the loop, increment inside the relevantif coin == X
block, then print the results at the end.持续跟踪头部数量:
Keep a running track of the number of heads:
您可以使用
random.getrandbits()
一次生成所有 100 个随机位:输出
You could use
random.getrandbits()
to generate all 100 random bits at once:Output
我最终得到了这个。
I ended up with this.
这是我的代码。希望它会有所帮助。
Here is my code. Hope it will help.