![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Newbie
Join Date: Dec 2004
Posts: 2
Rep Power: 0
![]() |
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 += 1While 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. |
|
|
|
|
|
#2 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
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.
|
|
|
|
|
|
#3 |
|
Newbie
Join Date: Dec 2004
Posts: 2
Rep Power: 0
![]() |
D'oh!
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: |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|