Editor

Python Program to Simulate a Coin Toss

Beginner · Games and random numbers

A coin toss has two outcomes, heads or tails, each with an equal chance. This program tosses a coin ten times using the random module, prints each result, and counts how many heads and tails came up.

Program

coin_toss.py
import random
tosses = 10 # or: tosses = int(input("How many times should the coin be tossed? "))
heads = 0
tails = 0
for i in range(1, tosses + 1):
result = random.choice(["Heads", "Tails"])
print(f"Toss {i}: {result}")
if result == "Heads":
heads += 1
else:
tails += 1
print("Heads:", heads)
print("Tails:", tails)
Output
Toss 1: Tails
Toss 2: Heads
Toss 3: Tails
Toss 4: Tails
Toss 5: Heads
Toss 6: Heads
Toss 7: Tails
Toss 8: Tails
Toss 9: Tails
Toss 10: Heads
Heads: 4
Tails: 6

How it works

  1. random.choice(["Heads", "Tails"]) picks one of the two items with an equal chance, just like a fair coin.
  2. The loop tosses the coin tosses times and prints each result with its toss number.
  3. heads and tails count the results, and together they always add up to the number of tosses.
  4. The output changes on every run, and with only 10 tosses it is common to get 6 heads and 4 tails, or even 7 and 3.

Other ways to write it

Tossing 10000 times

Tossing 10000 times
import random
tosses = 10000
heads = 0
for i in range(tosses):
if random.random() < 0.5: # a random decimal from 0 up to 1
heads += 1
print("Heads:", heads, f"({heads / tosses:.1%})")
print("Tails:", tosses - heads, f"({(tosses - heads) / tosses:.1%})")
Output
Heads: 5019 (50.2%)
Tails: 4981 (49.8%)

With many tosses, the share of heads comes very close to 50%, which is called the law of large numbers. random.random() is below 0.5 half the time, and :.1% shows a fraction as a percentage.

Tossing until three heads in a row

Tossing until three heads in a row
import random
streak = 0
tosses = 0
while streak < 3:
toss = random.choice("HT")
tosses += 1
print(toss, end=" ")
if toss == "H":
streak += 1
else:
streak = 0 # a tail breaks the streak
print()
print("Three heads in a row after", tosses, "tosses")
Output
H T H T H T T H T T H H T H T T H T T H H H 
Three heads in a row after 22 tosses

A while loop suits a goal rather than a fixed count: it keeps tossing until the streak reaches 3, so the number of tosses is different every run.

Try it yourself

Toss two coins at once in each turn and count how often both show heads.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises