pythonrandomstatisticscoin-flipping

Python code for the coin toss issues


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?


Solution

  • 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 ")