Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   While And Random Problem [solved] (http://www.programmingforums.org/showthread.php?t=1535)

Corvus Dec 13th, 2004 7:25 PM

G'day all

I am working my way through a book called "Python programming for absolute beginners" (I have very little programming experience) and at the end of one chapter you are asked to write a simple coin toss programme that tosses a coin 100 times and prints the result of each toss either as "heads" or "tails" using a while loop. I can get the random to work without the loop but I can't get it working properly using the loop, each toss is exactly the same (eg 100 instances of "heads"), though randomly it will change to the other and every time I run the programme for some time it will generate that.

Here is the code:

:

# Coin Toss programme
# Flips 100 coins and reports heads or tails

# Stuart Graham 10/12/04

import random
coin = random.randrange(2)

count = 0
toss = int(raw_input("enter number of tosses "))

while (count < toss): *
 *if (coin == 0):
 * *print "heads", coin
 *else: #(coin == 1)
 * *print "tails", coin

 *count += 1


While fiddling I have tried things like having the count += 1 directly after the while and I have added the toss to see if it makes any difference. It hasn't, beyond allowing me to change the number of coins tossed. I have tried coin = random.randrange(0.0, 1.0). Everything I have tried ends up with the same result.

Any hints would be appreciated as this is bugging the living daylights out of me.

Ooble Dec 13th, 2004 7:54 PM

Put the coin = random... statement in the while loop. In your code, it's only being called once. You want it to be called every time.

Corvus Dec 13th, 2004 8:27 PM

D'oh! :rolleyes: Thank you, thank you, thank you! It works perfectly now, I wouldn't have thought of that at all. I will have to remember it for future programmes.

Thanks again :rock:


All times are GMT -5. The time now is 4:21 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC