[Tutor] while/if/elif/else loops

bob bgailer at alum.rpi.edu
Wed Nov 2 04:48:24 CET 2005


At 02:36 PM 11/1/2005, Zameer Manji wrote:
>Ok after looking at everyones replies my program looks like this:
>
>#Coin Toss Game
>#Zameer Manji
>import random
>
>print "This game will simulate 100 coin tosses and then tell you the
>number of head's and tails"
>
>tosses = 0
>heads = 0
>tails = 0
>
>while tosses<100:
>     if tosses<100:
>         coin = random.randrange(2)
>         tosses +=1
>         if coin == 0:
>             heads +=1
>             print "Heads"
>         else:
>             tails +=1
>             print "Tails"
>     else:
>         print "100 tosses have been simulated. Please wait for your results"
>
>print "Out of", tosses, ",", heads, "were heads and", tails, "were tails."

Good progress. Note that
     if tosses<100
will always succeed, since the while ends when tosses is 100. Therefore the 
first print statement never happens.

Here are some incremental refinements to help you get a taste of 
programming and Python

Refinement 1 put the first print where it will execute. But what is there 
to wait for?

>while tosses<100:
>         coin = random.randrange(2)
>         tosses +=1
>         if coin == 0:
>             heads +=1
>             print "Heads"
>         else:
>             tails +=1
>             print "Tails"
>print "100 tosses have been simulated. Please wait for your results"
>print "Out of", tosses, ",", heads, "were heads and", tails, "were tails."

Refinement 2 - use for and range() instead of while:

>for tosses in range(100):
>         coin = random.randrange(2)
>         if coin == 0:
>             heads +=1
>             print "Heads"
>         else:
>             tails +=1
>             print "Tails"
>etc.

Refinement 3 - test result of randrange directly:

>for tosses in range(100):
>         if  random.randrange(2):
>             tails +=1
>             print "Tails"
>         else:
>             heads +=1
>             print "Heads"
>etc.

Refinement 4 - compute heads once:

>for tosses in range(100):
>         if random.randrange(2):
>             tails +=1
>             print "Tails"
>         else:
>             print "Heads"
>heads = 100 - tails
>etc.

Radical Refinement 1 - use list comprehension instead of for. Use the sum 
function:

import random
coins = [random.randrange(2) for i in range(100)]
print "1 for heads, 0 for tails", coins
# 1 for heads, 0 for tails [1, 1, 1, 0, 1, 1, 0, 0, 1, 0 ...]
heads = sum(coins)
print "Heads %i Tails %i" % (heads, 100-heads)
# Heads 64 Tails 36

Have fun groking all there is to programming and Python. 



More information about the Tutor mailing list