The purpose of this in-class activity is to gain practice working
with for loops and to learn how to use the range
function. It will also continue with the use of random numbers.
Coin flipping is used in many different types of scientific simulations, as well as in game programming. In this exercise, you are going to write a function that simulates flipping a coin some number of times (to be determined by the user). The function will print out "heads" or "tails" each time the coin is flipped, and will print out the total number of heads and tails at the end. The following steps will help you to write this function.
coinFlip, that
does not take any arguments.
for loop statement
that will iterate the number of times that the
user specified. You will need to use the
range function to do this. The
range function returns a set of
numbers to be iterated over. For example,
range(3) returns 3 numbers, precisely 0, 1, and
2, whereas range(5) would give us 0,
1, 2, 3, 4.
for loop, you will do the following:
numHeads and
numTails. These variables should be
assigned the value 0.
if/else blocks of code,
increment the counter variables by 1. There are
two ways to choose from to do this:
num = num + 1
or
num += 1
where num is the name of your variable.
Enter the number of times to flip the coin: 3
Heads
Tails
Heads
The number of times the flip ended in heads was: 2
The number of times the flip eneded in tails was: 1
Starting number of organisms: 2
Average daily increase: 0.30
Number of days to multiply: 10
Day Approximate Population
1 2
2 2.6
3 3.38
4 4.394
5 5.7122
6 7.42586
7 9.653618
8 12.5497034
9 16.31461442
10 21.20898746000002
for loop to iterate the number of times the
user specified.
numOrganisms = numOrganisms + numOrganisms * dailyIncr
Stop and Think: What are good values to test? How do you know what the approximate population values should be? Should you calculate some of these by hand to make sure your program is working correctly?