beginner code problem
Rob Johnson
prophet621 at cox.net
Fri Jun 2 20:09:30 EDT 2006
On 2006-06-02 19:25:28 -0400, John Machin <sjmachin at lexicon.net> said:
> Thanks for the reply John. I seem to be getting all the same problems
> with your code that I had with mine so it may be an issue with Python
> on this computer though I haven't had one prior to now. I'm running it
> on OSX Tiger so I'll give it a shot on my Windows box. With pythons
> portability I didn't think it would be an issue so didn't mention it in
> the post.
The different problems I was having was a result of moving some of
the code around thinking I had messed up and trying to fix it. The code
I posted was just running but never stopping to give the the output.
Thanks for explaining about getting a new value for flip, I wasn't
positive about that and you really helped clear up any confusion I was
having.
Rob
>
> This can't happen with the code that you posted. It *could* happen if
> the statement count += 1 was not being executed once each time around
> the while loop -- like if it was *not* indented.
>
> # Bad code #1
> import random
> flip = random.randrange(2)
> heads = tails = count = 0
> while count < 100:
> if flip == 0:
> heads += 1
> else:
> tails += 1
> count += 1
> print "The coin landed on heads", heads, 'times ' \
> "and tails", tails, 'times'
>
>> A few times I would get it to print 'heads 0 (or 1) times and tails 1
>> (or 0) times' 100 times.
>
> Again, can't happen with the code you have posted. If it is printing
> 100 times, that would be because you have indented the print statement
> so that it is being executed once each trip around the loop.
>
> # Bad code #2
> import random
> flip = random.randrange(2)
> heads = tails = count = 0
> while count < 100:
> if flip == 0:
> heads += 1
> else:
> tails += 1
> count += 1
> print "The coin landed on heads", heads, 'times ' \
> "and tails", tails, 'times'
>
>>
>> Here's the code I wrote:
>>
>> import random
>>
>> flip = random.randrange(2)
>> heads = 0
>> tails = 0
>> count = 0
>>
>> while count < 100:
>
> To help you see what is happening, insert a print statement here; e.g.:
> print flip, count, heads, tails
>>
>> if flip == 0:
>> heads += 1
>> else:
>> tails += 1
>>
>> count += 1
>>
>> print "The coin landed on heads", heads, 'times ' \
>> "and tails", tails, 'times'
>>
>
> The code that you posted sets flip only once i.e. only 1 toss, not 100.
> If it is 0, you get 100 heads and 0 tails. Otherwise you get 0 heads
> and 100 tails. You need to get a new value for flip each trip.
>
> # Not quite so bad code
> import random
> heads = tails = count = 0
> while count < 100:
> flip = random.randrange(2)
> # print flip, count, heads, tails # un-comment as/when required :-)
> if flip == 0:
> heads += 1
> else:
> tails += 1
> count += 1
> print "The coin landed on heads", heads, 'times ' \
> "and tails", tails, 'times'
>
> HTH,
> John
More information about the Python-list
mailing list