[Tutor] Loop

Alan Gauld alan.gauld at btinternet.com
Sun Jun 5 02:04:16 CEST 2011


"Vincent Balmori" <vincentbalmori at yahoo.com> wrote

> you the number of heads and tails." Right now I am 
> having trouble connecting the random.randint function 
> into the loop.

Break the problem statement down.
You have correctly worked out that randint(1,2) will equate 
to tossing the coin.

You want to do that 100 times so it must be inside 
a loop that repeats 100 times. The normal loop to 
choose for a fixed number of repititions is a for loop:

for count in range(100):
       result = randint(....)

And you know how to work out if its heads or tails 
based on result, so that also goes in the loop.
(Hint: You only really need one of them since the 
other is 100-X)

> while toss < 100:
>    toss += 1
>    coin = input(random.randint(1,2)

I have no idea what this is doing, and I suspect 
neither do you! Did you try walking it through in 
your head? ( Hint: In programming never guess 
what your code might do, be sure. Its easier 
to debug that way!)

> print("Toss Count:", count)
> print("Tails:", tails)
> print("Heads:", heads)

Yep, that bit oughta work.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list