Connecting Tech Pros Worldwide Help | Site Map

coin flip

  #1  
Old October 3rd, 2008, 06:45 PM
Newbie
 
Join Date: Oct 2008
Posts: 4
I am creating a python program that will flip a coin 100 times and then tells you the number of heads and tails. This is for a class I am taking, I am not looking for the answer. I have already started writing the program, but something is missing because it will not run...can someone let me know if they can see my error?

import random
heads=0
tails=0
count=1
while count <101:
randomFlip = random.randrange(0,1)
if randomFlip == 0:
heads = heads + 1
else:
tails = tails + 1
count = count + 1
print heads," heads"
print tails," tails"
  #2  
Old October 3rd, 2008, 07:45 PM
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 482

re: coin flip


I see two things wrong with the code you have there. One is that not all the code in the while loop is indented enough. You need to have it be:
Expand|Select|Wrap|Line Numbers
  1. while count <101:
  2.     randomFlip = random.randrange(0,1)
  3.     if randomFlip == 0:
  4.         heads = heads + 1
  5.     else:
  6.         tails = tails + 1
  7.     count = count + 1
  8.  
Indent everything inside the loop, and if something is inside an if statement inside of a loop, it has to be indented twice.

The other thing is that random.randrange(0,1) will not pick either zero or one. It will choose a random integer that is greater than or equal to zero, but less than one. Not much of a choice. Your program picks all heads. Make it pick a random integer that is greater than or equal to zero but less than 2 with random.randrange(2).

And when you are posting code, please put [CODE] before it and [/CODE] after it, so it shows up in a nice little box.

Hope this helps.

Last edited by boxfish; October 3rd, 2008 at 07:45 PM. Reason: Saying please.
  #3  
Old October 3rd, 2008, 09:40 PM
Newbie
 
Join Date: Oct 2008
Posts: 4

re: coin flip


Thanks for your input...it helped a lot!
  #4  
Old October 4th, 2008, 06:21 PM
Newbie
 
Join Date: Sep 2008
Posts: 18

re: coin flip


Maybe you could look into the random.randint() function... play about with it in IDLE.

Expand|Select|Wrap|Line Numbers
  1. >>> import random
  2. >>> help(random.randint)
  3. Help on method randint in module random:
  4.  
  5. randint(self, a, b) method of random.Random instance
  6.     Return random integer in range [a, b], including both end points.
  7.  
-freddukes
Reply


Similar Threads
Thread Thread Starter Forum Replies Last Post
Coin flipping program problem blackstormdragon answers 6 February 12th, 2007 04:18 PM
Flip a coin 100 times and get result for both sides coolindienc answers 0 December 4th, 2006 06:39 PM
coin toss problem celerysoup16@hotmail.com answers 52 June 19th, 2006 10:25 PM
Basic coin flipper program - logical error help DannyB answers 12 February 22nd, 2006 04:25 PM