[Tutor] While Loops: Coin Flip Game :p:

Alan Gauld alan.gauld at btinternet.com
Tue Nov 16 23:46:35 CET 2010


"Stephanie Dawn Samson" <sdawn at live.ca> wrote

>  thought I should write the rewritten code I got that others helped 
> me get to

By applying a couple of other ideas that have been suggested you get
something shorter and arguably slightly clearer:

# Coin Flips
# The program flips a coin 100 times and then
# tells you the number of heads and tails

import random

print """
    Welcome to 'Coin Flipper!'
I will flip a coin 100 times and then tell you
the number of heads and tails!
"""
headsCount = 0

for count in range(100):
    if random.randrange(2):  # returns 1/0 => true/False
           headsCount += 1

print "The number of heads was", headsCount
print "The number of tails was", 100-headsCount
raw_input("\n\nPress the enter key to exit.")


And you could replace the whole for loop with a generator expression
if you really wanted to, but I suspect that is getting into advanced
territory for you at this stage...

HTH,


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





More information about the Tutor mailing list