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?
Keep a running track of the number of heads:
You could use
random.getrandbits()
to generate all 100 random bits at once:Output
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.