Welcome, guest | Sign In | My Account | Store | Cart

This Python Script flips a coin a user defined number of times and returns the frequency and relative frequency for heads and tails.

Python, 53 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from decimal import Decimal, getcontext
from random import randint

# Return 3 decimal places

getcontext().prec = 3

# Function "get_input" verifies the input. As "raw_input" does not accept an int
# as input (which is what we need), the function converts the input into a str
# and checks whether the str is a digit. If so it converts the str to an int and
# returns it. If not the user is prompted again for an input. A float is not a
# valid input ("isdigit" would not be True). You can convert an int to a str but
# not a float to a str. The return value is used to define the number of trials.

def get_input(prompt):
    ''' (str) --> int
    Ask the user for input, convert it into a str, check for a digit and convert
    into an int. Prompt as long as the user provides a valid input.
    '''
    trials = raw_input(prompt)
    trials = str(trials)
    while not trials.isdigit():
        print "You have to provide an integer for the number of flips!"
        trials = raw_input(prompt)
    return int(trials)

heads = 0
tail = 0
i = 0

print "\n"

flip = get_input("How often shall I flip a coin? ")

print "\nFlipping the coin ..."

while i < int(flip):
    coin = randint(1,2)
    if coin == 1:
        heads += 1
    else:
        tail += 1
    i += 1

relfreq_heads = Decimal(heads) / Decimal(int(flip))
relfreq_tail = Decimal(tail) / Decimal(int(flip))  

print "\nFlipping a coin", flip, "times yields:\n"

print "Outcome\t\tFrequency\tRelative Frequency"
print "=======\t\t=========\t=================="
print "Heads\t\t", heads, "\t\t", relfreq_heads
print "Tail\t\t", tail, "\t\t", relfreq_tail

3 comments

Steven D'Aprano 10 years ago  # | flag

When you have a fixed number of loops, it is easier and better to let Python do the counting instead of yourself:

# Don't do this:
number_of_loops = 20
i = 0
while i < number_of_loops:
    do_some_stuff
    i += 1

# Instead do this:
number_of_loops = 20
for i in range(number_of_loops):
    do_some_stuff
Oscar 10 years ago  # | flag

Does using range as above in the comment increase the memory footprint of the program?

Steven D'Aprano 9 years, 2 months ago  # | flag

Oscar: not in any meaningful sense.

In Python 2, if you ask for a huge number of trials, say ten billion, then using range will use a lot of memory. But the solution is to use xrange instead.

In Python 3, just use range. Its memory footprint is negligible.