[Tutor] Issue w/ program: Flip a coin and count heads and tails

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Fri May 24 13:52:05 CEST 2013


On 24 May 2013 12:01, Rafael Knuth <rafael.knuth <at> gmail.com> wrote:
> Hello,
>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times and
> then counts the number of heads and tails. It obviously does something else
> than I intended, and I am wondering what I did wrong:
>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
>
> heads = 0
>
> tails = 0
>
> while flips < 10:
>
>     flips = flips + 1
>
>     if random.randint(1,2) == 1:
>
>         heads = heads + 1
>
>         print("We've got " + str(heads) + " heads here."
>
>     if random.randint(1,2) == 2:
>
>         tails = tails + 1
>
>         print("We've got " + str(tails) + " tails here.")
>
> This is what I get as output:
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
>
> We've got 1 heads here.
>
> We've got 2 tails here.
>
> We've got 2 heads here.
>
> We've got 3 tails here.
>
> We've got 3 heads here.
>
> We've got 4 tails here.
>
> We've got 5 tails here.
>
> We've got 4 heads here.
>
> We've got 6 tails here.
>
> We've got 7 tails here.
>
> We've got 5 heads here.
>

You're printing from within your while loop, so *everytime* through it, your
program prints either the heads or the tails message.
In addition, your throwing the coin twice during each run of the loop:
if random.randint(1,2) == 1   # that's one
if random.randint(1,2) == 2   # that's another one

flip the coin once instead and store the outcome in a variable, like:
result = random.randint(1,2)

if result == 1:
   # do head stuff here
else:
   # do tail stuff here

That should fix the unexpected behavior. However, if all you want to do is,
as you say, count the total numbers of head and tail results, this is an
incredibly complicated way to do it.
This short form suffices:

import random

flips = 10
s = sum(random.randint(0,1) for flip in range(flips))

print ("We've got " + str(flips-s) + " heads and " + str(s) + " tails here.")

Read about range, comprehensions and generator expressions if you have
trouble understanding the third line.
Best,
Wolfgang





More information about the Tutor mailing list