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!
Further Reading
How to Write to a File in Python
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
Python2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)
JavaScript2023.02.16JavaScript How to Get Selected Text from a Textbox
JavaScript2023.02.15JavaScript Select All Text in Div with a Mouse Click