[Tutor] Coin Flipping Program

Alan Gauld alan.gauld at btinternet.com
Sun Aug 21 19:34:34 CEST 2011


On 21/08/11 17:14, Joel Preston wrote:

> tells you the number of heads and tails that come up.  So far I can
> write a program that will flip a coin 100 times but it will only come up
> tails or heads all 100 times.

Look again at your code, you only assign a value to coin once, before 
you enter the loop.

 > import random
 >
 > print('Flip the coin 100 times and see how many times tails come up.')
 > input('Flip...')
 >
 > # Set initial values
 >
 > coin = random.randint(1, 2)

This is the only assignment.

 > tries = 0
 >
 > # flipping loop
 > while tries != 100:

In general if you are looping for a fixed number of times its easier to 
use a for loop:

for tries in range(100):
 >    if coin == 1:
 >        print("heads")
 >    else:
 >        print("tails")
 >
 >    input("Flip again...")

You ask the user to flip but you never assign a new value
So you need to add an assignment line inside the lop.
The easiest way is just to move the existing line above down
to the start of the loop code.


HTH,

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



More information about the Tutor mailing list