I would avoid using the Python shell to write multiline programs. Use one of the Python editors like IDLE, wirte your program, save it and run it. This would have given you an error message like:
NameError: name 'timesflipped' is not defined
Using FengG's advice your program should look like this:
import random
coin_heads, coin_tails, timesflipped = 0,0,0
while timesflipped <100:
coin_flips = random.randrange(2)
if coin_flips == 0:
coin_heads = coin_heads + 1
else:
coin_tails = coin_tails + 1
timesflipped += 1
print "Out of 100 flips " + str(coin_heads) + " were heads and " + \
str(coin_tails) + " were tails."
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
Hey I did this in class the other week. This code is simple and works perfectly
import random
Num = int(raw_input("enter number of coin flips:"))
coinf = 0
h = 0
t = 0
while coinf < Num:
coinf = coinf + 1
rand = random.randint(0,2)
if rand == 1:
h = h + 1
else:
t = t + 1
print h, "heads",t, "tails"
What kind of a grade did you get. Hopefully your teacher did not give a passing one. Run this modified version and see if you can tell why you will always get approximately twice as many tails as heads.
import random
Num = int(raw_input("enter number of coin flips:"))
flips_dic = {}
coinf = 0
h = 0
t = 0
while coinf < Num:
coinf = coinf + 1
rand = random.randint(0,2)
if rand not in flips_dic:
flips_dic[rand] = 0
flips_dic[rand] += 1
if rand == 1:
h = h + 1
else:
t = t + 1
print h, "heads",t, "tails"
print flips_dic
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Hopefully your teacher did not give a passing one.
That was a joke BTW. It's an easy mistake to make.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714