To write a Python coin toss program, you need to randomly choose between heads and tails.
To do this:
- Create a list with heads and tails.
- Randomly select an element from the list.
- Return the randomly selected item.
Here is how it looks in code:
import random def cointoss(): return random.choice(["Heads", "Tails"])
Now you can call this function to randomly flip a coin. For example, let’s toss a coin three times:
t1 = cointoss() t2 = cointoss() t3 = cointoss() print(t1, t2, t3)
Example outcome:
Heads Tails Heads
How to Simulate Coin Toss in Python without random.choice()
If you are on a Python course and you are not allowed to use random.choice() function, there is another alternative to simulate coin flipping with Python:
- Create a list that has both heads and tails as outcomes.
- Randomly choose an index between 0 and 1.
- Access the coin toss outcome list with the randomly chosen index.
Here is how it looks in code:
import random def cointoss(): rand_i = random.randint(0, 1) outcomes = ["Heads", "Tails"] return outcomes[rand_i] # Toss a coin 3 times t1 = cointoss() t2 = cointoss() t3 = cointoss() print(t1, t2, t3)
Example outcome:
Tails Heads Tails
Conclusion
Today you learned how to flip a coin fairly in Python.
To recap, the easiest way to simulate coin toss is by using random.choice() function. This function randomly selects an outcome between heads or tails.
Thanks for reading.
Happy coding!