Coin Flip in Python

Python game 16 of 20

Beginnerโฑ 15 min๐Ÿ“„ 33 lines of Pythonโ˜… 3 challengesโ–ถ Plays in your browser

A coin flip is the simplest random event there is, which makes it the perfect place to start with Python's random module. In this game you call heads or tails ten times and see your score. Then the computer flips 10,000 coins in a blink to show how close to 50% the results really get.

It is half game, half science experiment: you'll also find the longest run of heads or tails, which is usually longer than people expect.

Play Coin Flip Challenge

coin_flip.py ยท real Python in your browser
Press โ–ถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (33 lines)

How to play

  • Type h for heads or t for tails, ten times.
  • Each right call scores a point.
  • Afterwards, watch the computer flip 10,000 coins.

The complete Coin Flip Challenge code

Here is the whole program (33 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.

import random

SIDES = {"h": "heads", "t": "tails"}

print("COIN FLIP CHALLENGE  -  call 10 flips")
score = 0
for flip in range(1, 11):
    call = input(f"Flip {flip}: heads or tails? (h/t) ").strip().lower()
    while call not in SIDES:
        call = input("Type h or t: ").strip().lower()
    coin = random.choice(["heads", "tails"])
    if SIDES[call] == coin:
        score += 1
        print(f"  It's {coin}. Correct!")
    else:
        print(f"  It's {coin}. Unlucky.")

print(f"\nYou called {score} out of 10.")
if score >= 7:
    print("Are you reading the coin's mind?")
elif score <= 3:
    print("Tough luck. Pure chance says about 5.")

# The experiment: flip lots of coins
flips = [random.choice("HT") for _ in range(10000)]
heads = flips.count("H")
print(f"\n10,000 flips: {heads} heads ({heads / 100:.1f}%), {10000 - heads} tails")

longest, run = 1, 1
for a, b in zip(flips, flips[1:]):
    run = run + 1 if a == b else 1
    longest = max(longest, run)
print(f"Longest run of the same side: {longest} in a row")

How the Coin Flip Challenge game works, step by step

01Flip a coin

random.choice(["heads", "tails"]) picks one of the two with equal chance. That one line is the whole coin.

coin = random.choice(["heads", "tails"])

02Count ten rounds with for

When you know exactly how many times to repeat, use for flip in range(1, 11). It counts 1 to 10 (the end number is left out).

for flip in range(1, 11):

03Flip ten thousand coins

A list comprehension builds 10,000 flips, and .count("H") counts the heads. :.1f in the f-string shows one decimal place.

flips = [random.choice("HT") for _ in range(10000)]
heads = flips.count("H")

04Find the longest run

zip(flips, flips[1:]) pairs each flip with the next one. If they match, the run grows; if not, it starts again at 1.

for a, b in zip(flips, flips[1:]):
    run = run + 1 if a == b else 1
    longest = max(longest, run)

What you'll learn

  • random.choice()
  • for loops with range()
  • Counting with .count()
  • Percentages and f-string formatting
  • Simulations: letting the computer experiment

Python concepts in this game:

Coin Flip Challenge coding challenges

Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).

1/3

Score the calls

Read 5 calls with input() (h or t). The coin results are fixed in RESULTS. Print exactly Score: 3/5 with the real score.

challenge 1 ยท edit, Run, then Check
Hint

if call == RESULTS[i]: score += 1, then print(f"Score: {score}/5").

Show a solution
RESULTS = ["h", "t", "t", "h", "h"]
score = 0
for i in range(5):
    call = input("h or t? ")
    if call == RESULTS[i]:
        score += 1

print(f"Score: {score}/5")
2/3

Percentage of heads

Write heads_percent(flips): flips is a string like "HTTHH". Return the percentage of heads rounded to 1 decimal place (60.0 here). Return 0.0 for an empty string.

challenge 2 ยท edit, Run, then Check
Hint

flips.count("H") / len(flips) * 100, then round(..., 1). Check for an empty string first.

Show a solution
def heads_percent(flips):
    if not flips:
        return 0.0
    return round(flips.count("H") / len(flips) * 100, 1)

print(heads_percent("HTTHH"))
3/3

Longest run

Write longest_run(flips): return the length of the longest run of the same letter in a row in a string like "HHTTTH" (3 here). Return 0 for an empty string.

challenge 3 ยท edit, Run, then Check
Hint

Compare each flip with the one before: same means run += 1, different means run = 1.

Show a solution
def longest_run(flips):
    if not flips:
        return 0
    longest = run = 1
    for i in range(1, len(flips)):
        if flips[i] == flips[i - 1]:
            run += 1
        else:
            run = 1
        longest = max(longest, run)
    return longest

print(longest_run("HHTTTH"))

Make it your own

Once your challenges pass, try one of these upgrades:

  • Let the player bet points on each flip.
  • Plot the running percentage of heads with matplotlib.
  • Simulate a biased coin that lands heads 60% of the time.
  • Find how many flips it takes on average to get 5 heads in a row.

Frequently asked questions

How do you flip a coin in Python?

import random, then random.choice(['heads', 'tails']). random.randint(0, 1) also works if you treat 0 as heads and 1 as tails.

Why aren't 10 flips always 5 heads and 5 tails?

Each flip is independent, so small samples wobble a lot. With 10,000 flips the share of heads gets very close to 50%.

How long is the longest run in 10,000 flips?

Usually around 12 to 15 in a row. Runs that long feel impossible, but they are normal in big random samples.

More games like this