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
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
random.choice(["Heads", "Tails"])picks one of the two items with an equal chance, just like a fair coin.- The loop tosses the coin
tossestimes and prints each result with its toss number. headsandtailscount the results, and together they always add up to the number of tosses.- 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises