Connecting Tech Pros Worldwide Forums | Help | Site Map

coin flip

Newbie
 
Join Date: Oct 2008
Posts: 4
#1: Oct 3 '08
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"

boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#2: Oct 3 '08

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.
Newbie
 
Join Date: Oct 2008
Posts: 4
#3: Oct 3 '08

re: coin flip


Thanks for your input...it helped a lot!
Newbie
 
Join Date: Sep 2008
Posts: 18
#4: Oct 4 '08

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