[Tutor] Challenge

Daniel Sarmiento dsarmientos at gmail.com
Tue Sep 22 17:48:38 CEST 2009


> Date: Tue, 22 Sep 2009 05:13:32 -0700 (PDT)
> From: Ali Sina <seena_blk at yahoo.com>
> To: tutor at python.org
> Subject: [Tutor] Challenge
> Message-ID: <826729.63168.qm at web45911.mail.sp1.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hello tutor
>
> I downloaded a guide about learning Python by Michael Dawson which has challenges at the end of each chapter. I'm a novice so I encountered a problem with this challenge:
>
> "Write a program that flips a coin 100 times and then tells
> you the number of heads and tails."
> I wrote this code but I know its wrong. Although it works properly:
>
> flips=0
> h='heads'
> t='tails'
> while True:
> ??? flips+=1
> ??? if flips>100:
> ??????? break
> ??? if True:
> ??????? print(flips,'=',h or t)
>
> But it prints every number with the string 'heads'. I'm really blank at this. It may have something to do with the 'random' module.
>
> Regards
>

You could use a dictionary to store the outcome and a list with the 
possible outcomes, then use random.choice to pick an outcome.

Here is my try at it:

In [18]: from random import choice

In [19]: pos = ('head', 'tail')

In [20]: outcomes = {'head':0, 'tail':0}

In [21]: for i in range(100):
    ....:     outcomes[choice(pos)] += 1
    ....:
    ....:

In [22]: print outcomes
-------> print(outcomes)
{'head': 46, 'tail': 54}

HTH

Daniel Sarmiento.


More information about the Tutor mailing list