[Tutor] Coin flip game

Jones, Lawrence D lawrence.jones at imperial.ac.uk
Thu Feb 11 23:15:14 CET 2010


I'm new to the list and to Python. I'm reading through Michael Dawson's 'Python programming: for absolute beginners' and at the end of chapter 3 he's set a challenge where the reader has to create a coin flip game. My code now works, but only after I randomly switched pieces of the code around and, basically, pulled my hair out because it wouldn't work.

My code is below. But can someone please explain to me why the following variable has to be placed where it is for the code to work? I thought it would need to go nearer the start of the code i.e. just before heads = 0, tails = 0 etc:

                coin = random.randrange(2)

Also, why does the randrange integer have to be '2'? I only discovered this worked by complete accident. I tried '1' and '0,1' as my integers but they just didn't work.



import random
print "The Coin Flip Game\n"

heads = 0
tails = 0
count = 0

while count < 100:
    coin = random.randrange(2)
    if coin == 0:
        heads = heads + 1
        tails = tails + 1
    count += 1

print "Heads: ", heads
print "Tails: ", tails

raw_input("\nPress enter to exit.")

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100211/27d8079b/attachment-0001.htm>

More information about the Tutor mailing list