beginner code problem

John Machin sjmachin at lexicon.net
Sat Jun 3 01:25:28 CEST 2006


On 3/06/2006 8:41 AM, RJ wrote:
>  I'm trying to teach myself Python (probably running into the old dog 
> new tricks issue) and I'm trying to start with the very basics to get a 
> handle on them.
> 
>  I'm trying to write code to get the computer to flip a coin 100 times 
> and give me the output of how many times heads and tails. After solving 
> a few syntax errors I seem to be stuck in an endless loop and have to 
> kill python.

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