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
random.choice()gives each item in the list the same chance, so heads and tails each have a 50% chance.- The seed makes the result the same every time the page is built. Remove the
random.seed(...)line and each run can give a different side.
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%)
- Every toss is either heads or tails, so
heads + tailsis always 1000. - The format
:.1%multiplies the number by 100, shows one decimal place and adds the%sign.0.5prints as50.0%.
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.