Basic coin flipper program - logical error help

Martin P. Hellwig mhellwig at xs4all.nl
Tue Feb 21 19:42:16 EST 2006


DannyB wrote:
 > I'm just learning Python.

So am I :-)

 > I've created a simple coin flipper program -
 > here is the code:
 >
 > [source]
 > #Coin flipper
 > import random
 >
 > heads = 0
 > tails = 0
 > counter = 0
 >
 > coin = random.randrange(2)
 >
 > while (counter < 100):
 >     if (coin == 0):
 >         heads += 1
 >         counter += 1
 >     else:
 >         tails += 1
 >         counter += 1
 >
 > coin = random.randrange(2)

This line is you logic error because it's not part of your while loop 
the coin variables get the result of random.randrange(2) assigned only 
one time (before the loop).

 >
 >
 > print "\nThe coin landed on heads", heads, "times."
 > print "\nThe coin landed on tails", tails, "times."
 > [/source]
 >
 > <<<I'm sure the [source] tags don't work - I through them in there
 > anyway.>>>
 >
 > The program runs - however - it will give me 100 heads OR 100 tails.
 > Can someone spot the logic error?
 >
 > Thanks
 >
 > ~Dan
 >

You could changed the program to this it works too and is just as 
readable (IMHO):

#Coin flipper
import random

heads = 0
tails = 0
counter = 0
				# removed random line
while (counter < 100):
     if random.randrange(2):	# put random here
         heads += 1
         counter += 1
     else:
         tails += 1
         counter += 1
				# removed random line
print "\nThe coin landed on heads", heads, "times."
print "\nThe coin landed on tails", tails, "times."

Take my advice with caution I'm also new to this :-)

Btw, it is possible that the coins lands on it side if not catched with 
the hand (yes I have seen it happen) ;-)

-- 
mph



More information about the Python-list mailing list