coin flip
I need to have 4 functions which asks the user how many times to flip the coin and then displays the number of heads and the number of tails as a decimal?
def getInputs():
times=input("please enter the number of times the coin should be flipped: ")
def simulateFlips():
for i in range(times):
if randint(1,2) == 1:
print "Heads"
else:
print "Tails"
def main():
getInputs()
main()
def displayResults():
simulateFlips()
gangster88
Junior Poster in Training
65 posts since Nov 2009
Reputation Points: 10
Solved Threads: 0
So you just want to output the percentage calculation for heads and tails?
Wouldn't you just divide the number collected by the total sample size?
Murtan
Practically a Master Poster
671 posts since May 2008
Reputation Points: 344
Solved Threads: 116
What does your code look like?
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Well, you are almost there. A few minor changes, see the comments in the modified code ...
def main():
times = getInputs()
heads, tails = simulateFlips(times)
displayResults(heads, tails, times) # added times to args
def getInputs():
times = int(raw_input("please enter the number of times the coin should be flipped: "))
return times
def simulateFlips(times):
import random
heads = 0
tails = 0
for i in range(times):
if random.randint(1,2) == 1:
heads += 1
else:
tails += 1
return (heads, tails) # moved return out of the for loop
def displayResults(heads, tails, times):
print heads, tails, times # for testing only
print (100.0*heads/times),"Heads Probability." # changed formula a little
print (100.0*tails/times), "Tails Probability."
main()
Note that a temporary test print is a good idea for trouble shooting. Also in Python2 something like 8/10 is an integer division and will give a zero, introducing a float like 8.0/10 will make it a floating point division. In Python3 this has been updated such that/ is a floating point division and // is an integer division.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
This function returns on the first pass through the loop.
def simulateFlips(times):
import random
heads = 0
tails = 0
for i in range(times):
if random.randint(1,2) == 1:
heads += 1
else:
tails += 1
return (heads, tails)
## it should be
return heads, tails
Also you have to convert to a float when dividing
print (float(heads)/times*100), "Heads Probability."
and pass "times" to the function displayResults.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
The return statement is still in the wrong place. You return from the function after the first flip. See Vegaseat's or my previous post.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714