Simulate coin flipping in python

Coin flipping is the practice of throwing a coin in the air and checking which side it lands on. It’s commonly used as an unbiased way to solve a dispute, and it can me modeled using computer programming. Let’s create a simple script In python that asks the user for input and depending on what they entered provides output on whether the coin landed on heads or tails. Here’s the breakdown of the logic that we can use:

  1. Need to store the options of head or tail in a container type.
  2. Need to determine the side the coin fell on.
  3. Need to read in the input from the user.
  4. Need to compare the user’s input to the result.
  5. Need to give the user an option to exit from the simulation.

Let’s translate each component to the respective python code.

1) This can be done by using a tuple:

coin = ('heads', 'tails')

2) This can be done by using the choice() function in the random module:

flip = random.choice(coin)

3) To read in user input use the input() function in python as indicated below:

your_choice = input('Type heads or tails: ')

4) This can be done by using an if statement as indicated below:

if your_choice == flip:

5) This can again be done by using a conditional statement like in the following:

if your_choice == 'x' or your_choice == 'X':

We can wrap the above logic in a while loop, and print the data that’s been generated once the program is exited out of. Below is the script:

import random
coin = ('heads', 'tails')
heads, tails = 0, 0
games = 0
print('Hit x to exit')
while True:
    flip = random.choice(coin)
    your_choice = input('Type heads or tails')
    if your_choice == 'x' or your_choice == 'X':
        print("GAME OVER :(")
        print('Coin flipping stats:')
        print('Games played = {}'.format(games))
        print('heads = {}'.format(heads))
        print('tails = {}'.format(tails))
    if your_choice == flip:
        print('Coin landed on {}. Yeah boi you win!'.
        games += 1
        print("Uh oh. Coin landed on {}. Better luck next "
        games += 1
    if flip == 'heads':
        heads += 1
    elif flip == 'tails':
        tails += 1
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.