Python Week – Day 2 – Simple Coin Flip Game

Follow the instruction from Day 1 to create another python project. In this python project, create a file called flip.py

How does a Coin Clip game work?

Normally, it works by someone tossing a coin, which can be a tail or a head, and another person guess before toss. The guesser wins if the guess matches.

If this coin is a perfectly made coin, there should be a 50/50 chance that it would be head/tail.

A very simple coin flip game could work as follow:

  1. Ask for head or tail
  2. Flip a coin
  3. If the guess matches the result, then it’s a win

To build this game, I will work you through the steps, the simplest first, then onto

  1. Just print “flip a coin” and “It’s a head” to console
  2. Create a constant variable to hold the value of the coin flip, but pretend that the value is always “head”
  3. For better style and to reduce duplicate code, create a new file to store the constant variables. Use the constant variables in this new module.
  4. Create a placeholder variable called “random_val”, but set it to “0.50” (pretend it’s always 0.50) . Add code to check if random_val is larger than 0.50, if so, pring HEAD, else print TAIL
  5. Ask user for input for random_val (instead of pretend it is always 0.50)
  6. Instead of getting the random value from the user, get it by calling seed() and random() from the Python random module.
  7. Improve the “randomness” by using the current timestamp as “seed”. The coin flip should now be fair.
  8. Add the for loop, so that the coin is flipped 10 times in a roll
  9. Keep a tally of how many heads and tails are there after 10 coin flips
  10. Ask the user to enter the number of coin flips (instead of hard-coded it to 10)
  11. Beautify the output

Step 1: Just print “flip a coin” and “It’s a head” to console

Let’s print two lines to the console: (Note, the line that starts that “#” is a comment and is added to help you understand the code but will not be executed by python interpreter.

# print a value 
print("flip a coin");
print("It's a head");

Step 2: Create a constant variable to hold the value of the coin flip, but pretend that the value is always “head”

Next, let’s create a variable (“value”) to hold the value of the coin flip:

print("flip a coin");
print("It's a head");
# variable
value = "head";
# print the "concatenation" of a value and the value in a variable
print("It's a:" + value);

Step 3: For better style and to reduce duplicate code, create a new file to store the constant variables. Use the constant variables in this new module.

Notice the text (“head”)? That value is a “hard-coded” value and is best stored in a constant variable. A constant variable is a variable that holds a value but that value does not change. Let’s create a file to keep all the constant variables and import it to flip.py.

First create a new file called constant.py. Add the code to define two constant variables (HEAD and TAIL):

File constant.py

HEAD="head"
TAIL="tail"

Then update the flip.py to import the constant module (by adding “import constant” line). Use the variable (constant.HEAD) in the code.

File: flip.py

import constant

print("flip a coin");
print("It's a head");
# variable
value = "head";
# print the "concatenation" of a value and the value in a variable
print("It's a:" + value);
print("It's a:" + constant.HEAD);

Step 4:  Create a placeholder variable called “random_val”, but set it to “0.50” (pretend it’s always 0.50) . Add code to check if random_val is larger than 0.50, if so, pring HEAD, else print TAIL

import constant
# define a variable 
random_val = 0.50;
if (random_val> 0.50):
    print(constant.HEAD)
else:
    print(constant.TAIL)

 

Step 5: Ask user for input for random_val (instead of pretend it is always 0.50)

import constant
# take user input 
my_input = input("value=");

random_val = float(my_input)

# random_val = 0.50;
if (random_val> 0.50):
    print(constant.HEAD)
else:
    print(constant.TAIL)

 

Step 6: Instead of getting the random value from the user, get it by calling seed() and random() from the Python random module.

import constant
import random

random.seed(10)

print(random.random())
random_val = random.random();
if (random_val> 0.50):
    print(constant.HEAD)
else:
    print(constant.TAIL)

 

Step 7: Improve the “randomness” by using the current timestamp as “seed”. The coin flip should now be fair.

import random
import constant
import time

# ts stores the time in seconds
ts = time.time()
  
# print the current timestamp
print(ts)
# use timestamp as random number seed
random.seed(ts)
# generate pseudo random number
random_val = random.random();
# print the generated random number (ranging from 0 to 1)
print(random_val);
# If the generated random number is larger than 0.5, it's a head
# else it's a tail
if (random_val> 0.50):
    print(constant.HEAD)
else:
    print(constant.TAIL)

 

Step 8: Add the for loop, so that the coin is flipped 10 times in a roll

import random
import constant
import time

for i in range(10):
    # ts stores the time in seconds
    ts = time.time()

    # use timestamp as random number seed
    random.seed(ts)
    # generate pseudo random number
    random_val = random.random();

    # If the generated random number is larger than 0.5, it's a head
    # else it's a tail
    if (random_val> 0.50):
        print(constant.HEAD)
    else:
        print(constant.TAIL)

 

Step 9: Keep a tally of how many heads and tails are there after 10 coin flips

import random
import constant
import time

num_heads = 0
num_tails = 0
for i in range(10):
    # ts stores the time in seconds
    ts = time.time()

    # use timestamp as random number seed
    random.seed(ts)
    # generate pseudo random number
    random_val = random.random();

    # If the generated random number is larger than 0.5, it's a head
    # else it's a tail
    if (random_val> 0.50):
        print(constant.HEAD)
        num_heads += 1;
    else:
        print(constant.TAIL)
        num_tails += 1;

# print ( "number of heads=" + num_heads)
# print ( "number of tails=" + num_tails)
print ( "number of heads=" + str(num_heads))
print ( "number of tails=" + str(num_tails))

 

Step 10: Ask the user to enter the number of coin flips (instead of hard-coded it to 10)

import random
import constant
import time

num_flips = input("Please Ener Number of Flips= ");
num_flips = int(num_flips)

num_heads = 0
num_tails = 0
for i in range(num_flips):
    # ts stores the time in seconds
    ts = time.time()

    # use timestamp as random number seed
    random.seed(ts)
    # generate pseudo random number
    random_val = random.random();

    # If the generated random number is larger than 0.5, it's a head
    # else it's a tail
    if (random_val> 0.50):
        print(constant.HEAD)
        num_heads += 1;
    else:
        print(constant.TAIL)
        num_tails += 1;

print ( "number of heads=" + str(num_heads))
print ( "number of tails=" + str(num_tails))

Step 11: Beautifyl the result output

import random
import constant
import time

num_flips = input("Please Ener Number of Flips= ");
num_flips = int(num_flips)

num_heads = 0
num_tails = 0
for i in range(num_flips):
    # ts stores the time in seconds
    ts = time.time()

    # use timestamp as random number seed
    random.seed(ts)
    # generate pseudo random number
    random_val = random.random();

    # If the generated random number is larger than 0.5, it's a head
    # else it's a tail
    if (random_val> 0.50):
        print(constant.HEAD)
        num_heads += 1;
    else:
        print(constant.TAIL)
        num_tails += 1;

#Report 1: working
print ( "number of heads=" + str(num_heads))
print ( "number of tails=" + str(num_tails))
# Report 2: cleaner
print ( "number of heads=%3d" %( num_heads))
print ( "number of tails=%3d" %( num_tails))
# Report 3: cleanest
print ("number of %s = %i" % (constant.HEAD, num_heads)); 
print ("number of %s = %i" % (constant.TAIL, num_tails));

 

You can find the source code for this lesson at https://github.com/jess1sd/coinflip 

 

To learn more:

  • Create/Clone the coinflip project locally
  • Checkout https://www.codecademy.com/courses/learn-python-3 and review the concepts we have gone over today
  • Update the Coin Flip game so that it asks for “guess”, and if the guess matches the result, it’s a Win. Bonus (to get PlayStation swags
  • Build a Dice Throwing game  based on the Coin Flip
  • Checkout PyGame site https://www.pygame.org/news and build a simple game to share