PythonMastery

Coin toss program in Python

Toss a coin once with random.choice, then toss it 1000 times and count heads and tails with their percentages.

random.choice() picks one item from a list at random. With a list of the two sides of a coin, that is a coin toss.

The program

python
import random

random.seed(5)  # fixed seed so the output matches this page; remove it for real use

result = random.choice(["Heads", "Tails"])
print(f"The coin landed on: {result}")
output
The coin landed on: Tails

How it works

1000 tosses

Toss the coin many times and count each side. The percentages should be close to 50%, but they are rarely exactly 50%:

python
import random

random.seed(5)  # fixed seed so the output matches this page; remove it for real use

tosses = 1000
heads = 0
tails = 0

for _ in range(tosses):
    if random.choice(["Heads", "Tails"]) == "Heads":
        heads += 1
    else:
        tails += 1

print(f"Tosses: {tosses}")
print(f"Heads: {heads} ({heads / tosses:.1%})")
print(f"Tails: {tails} ({tails / tosses:.1%})")
output
Tosses: 1000
Heads: 498 (49.8%)
Tails: 502 (50.2%)

Longest streak

Long runs of the same side happen more often than most people expect. This program finds the longest run of the same side in 1000 tosses:

python
import random

random.seed(5)  # fixed seed so the output matches this page; remove it for real use

longest = 1
current = 1
previous = random.choice("HT")

for _ in range(999):
    side = random.choice("HT")
    if side == previous:
        current += 1
        longest = max(longest, current)
    else:
        current = 1
    previous = side

print(f"Longest streak in 1000 tosses: {longest}")
output
Longest streak in 1000 tosses: 12

random.choice("HT") picks one character from the string: "H" or "T". The first toss happens before the loop, so the loop runs 999 more times.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Modules & Imports