Now You Code 3: Coin Flips

Write a program to simulate 100,000 coin flips. The program should output the tally of heads and tails across the number of flips.

For Example: After 100000 flips. Heads: 50030, Tails 49970

Of course, since the flips are random, the counts will vary each time the program executes.

Your strategy should be to use a loop to flip a coin 100,000 times. After you flip you should check for heads or tails and increment the count accordingly.

How do you make Python simulate a coin flip?


In [11]:
# Sample code which demostrates how to flip a coin in python
import random 
coin = ['heads', 'tails']
flip = random.choice(coin)
print(flip)


heads

Run the cell above a couple of times. Notice how each time you execute the code, it comes up as either heads or tails.

Here's a breakdown of the code

line 1 imports the random module
line 2 sets up a coin to have two choices heads or tails
line 3 "flips" a coin by making a random choice among the values of the coin ('heads' or 'tails')
line 4 prints the results of the coin flip.

Now that you understand how to simulate a coin flip in Python, try to design an algorithm and then write code for the program.

Step 1: Problem Analysis

Inputs:

Outputs:

Algorithm (Steps in Program):


In [1]:
import random
# Step 2: write code for program


How many times should I flip the coin? 10000000
After 10000000 flips. Heads: 4999224, Tails 5000776

Step 3: Questions

  1. Which loop did you use to solve the problem? What it a definite or indefinite loop?

Answer:

  1. Modify this program to allow you to input the number of times you would like to flip the coin. NOTE: if you enter a large number, the program could take a few minutes to execute. Be Patient!!!

Answer:

  1. Explain how this progam could be modified to track flipping a "three" sided coin with heads, tails and foos for example? Do not modify the code, only explain your strategy.

Answer:

Step 4: Reflection

Reflect upon your experience completing this assignment. This should be a personal narrative, in your own voice, and cite specifics relevant to the activity as to help the grader understand how you arrived at the code you submitted. Things to consider touching upon: Elaborate on the process itself. Did your original problem analysis work as designed? How many iterations did you go through before you arrived at the solution? Where did you struggle along the way and how did you overcome it? What did you learn from completing the assignment? What do you need to work on to get better? What was most valuable and least valuable about this exercise? Do you have any suggestions for improvements?

To make a good reflection, you should journal your thoughts, questions and comments while you complete the exercise.

Keep your response to between 100 and 250 words.

--== Write Your Reflection Below Here ==--