抛硬币问题的Python代码 [英] Python code for the coin toss issues
本文介绍了抛硬币问题的Python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在用python编写一个程序,该程序模拟100次抛硬币并给出抛掷的总数.问题是我还想打印正面和反面的总数.
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.
这是我的代码:
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?
推荐答案
import random
total_heads = 0
total_tails = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("Heads!\n")
total_heads += 1
count += 1
elif coin == 2:
print("Tails!\n")
total_tails += 1
count += 1
print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")
这篇关于抛硬币问题的Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文