Hi everyone. I am just learning Python on class so I am really at the basic. I need to write a python program that will flip a coin 100 times and then tell how many times tails and heads were flipped. This is what I have so far but I keep getting errors.


>>>import random
>>> coin_heads, coin_tails, coin_flips = 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."

Problem is it returns this to me:
Out of 100 flips 0 were heads and 100 were tails.
Also everything is indented I just couldn't get it to show up in the post.

Any help is much appreciated. Thank you

The variable timesflipped used for the while loop is undefined before the comparison while timesflipped < 100: . This script should just return a NameError and not run.
Here's a fixed version:

import random

coin_heads, coin_tails, times_flipped = 0, 0, 0

timesflipped = 0  # <-- here's what I added.
while timesflipped < 100:
	coin_flips = random.randrange( 2 )
	if coin_flips == 0:
		coin_heads += 1
	else:
		coin_tails += 1
	timesflipped += 1
	

print "Out of 100 flips, " + str(coin_heads) + " were heads and " + str(coin_tails) + " were tails."

The above is the same, except that I declared timesflipped = 0 right before evaluating the while loop. Hope this helped!

Comments
thanks for spending your time on this!

if you want a program that tells you the total heads, tails, the percentage of both of these, prints the results in a easy format such as:

H
T
H
T

and allows you to export this data to a .txt file previously created i have already programmed such a program...

import random
import time

print "Coin Toss Program"
print "\nProgrammed by Devon McAvoy"

N = int(raw_input("\nNumber of times to flip the coin: "))

print "\n"

f = open('/probabilty/coin toss/coin toss.txt', 'w')

f.write('Coin Toss Program Results\n')
f.write('Coin Toss Programmed by Devon McAvoy\n')

nstr = 'The coin was flipped ' + repr(N) + ' times.'

f.write(nstr)
f.write('\n')

heads = 0
tails = 0
counter = 0

while (counter < N):
     if random.randrange(2):	
         heads += 1
         if heads > 0:
              print "H"
              f.write('H\n')
              time.sleep(.2)
         counter += 1
     else:
         tails += 1
         if tails > 0:
              print "T"
              f.write('T\n')
              time.sleep(.2)
         counter += 1
         
print "\nThe coin landed on heads", heads, "times."
print "\nThe coin landed on tails", tails, "times."
print "\nThe coin landed on heads", heads * 100 / N,"% of the time."
print "\nThe coin landed on tails", tails * 100 / N,"% of the time."
print "\n"

htot = 'The coin landed on heads ' + repr(heads) + ' times.'
ttot = 'The coin landed on tails ' + repr(tails) + ' times.'
hper = 'The coin landed on heads ' + repr(heads * 100 / N) + ' % of the time.'
tper = 'The coin landed on tails ' + repr(tails * 100 / N) + ' % of the time.'

f.write(htot)
f.write('\n')
f.write(ttot)
f.write('\n')
f.write(hper)
f.write('\n')
f.write(tper)
f.write('\n')

print "\nThank you for running Coin Toss."
print "\n"
print "\nWARNING: this program will close in 5 minutes."

f.write('Thank you for running Coin Toss.')

time.sleep(300)

also if you want a dice roll program and or a program that combines both of these just ask and i can deliver... i already have both programmed and i am currently working on a Yahtzee dice sim...

sadwickman got the easiest solution, the problem of your program is that you don't need to set coin_flips = 0 in the beggining, what you wanted to do is to initialize timesFlipped to 0.
so your first line should look like this :
coin_heads, coin_tails, timesFlipped = 0,0,0
the rests are good

I'm a newbie to, just did this weeks ago :)

Comments
Good observation

you must remember though that the easiest is not always the best solution... it could have a shortcut that will prevent you from adding to the code without having to rewrite the whole flippin thing... trust me i've had to do that... oh and pardon my pun...

Yes, Arrorn, but she said she was at a basic level, and it sounds like this program isn't really going to need much future expansion. It's a simple probability program consisting of very few lines. And even if it did, rewriting it requires pretty much no time to do. Plus, I know your code isn't very advanced either, but at a basic level, most people have trouble handling such large blocks of code together.
I hope the new program works for you Stephanie953! You should try to work your way through Arrorn's code though, it's a good resource too, and a great example of another step up.

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"

enjoy :)

Thanks very much for the help guys. Got the program working. :)

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."

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

Hopefully your teacher did not give a passing one.

That was a joke BTW. It's an easy mistake to make.

You understand the problem it contains right? rand = random.randint(0,2) can get either 0, 1, or 2. Then you have it check for a 1 as heads, and the else statement catches the 0 or 2 as a tails. Therefore, you have 2 chances for a tails for every one chance for a heads.

#Program to flip coin 100 times.

import random
y=1
x=100
head=0
tail=0

while y<=x:
    coin=random.randrange(2)+1

    if coin==2:
        head+=1

    elif coin==1:
        tail+=1

    if y<=x:
        y+=1

print ("head= "),head
print ("tail= "),tail

print ("Press Enter to exit! ")

Edited 3 Years Ago by pyTony: Fixed formatting

Attachments
#Program to flip coin 100 times.

import random
y=1
x=100
head=0
tail=0

while y<=x:
    coin=random.randrange(2)+1

    if coin==2:
        head+=1
        
    elif coin==1:
        tail+=1
        
    if y<=x:
        y+=1
        
print ("head= "),head
print ("tail= "),tail
 
print ("Press Enter to exit! ")

Why give a new coder such complicated responses?

Hopefully this simplifies it somewhat!

# Coin Flip (python 3)
# Simulates the flip of a coin 100 times and returns result to user
# Michael J Pannell 20 March 2013

import random

heads = 0
tails = 0
count = 0

while count < 100:


        coin = random.randrange(2)


    if coin == 0:
        heads += 1
    else:
        tails += 1
    count += 1

print("The Number of heads was", heads )
print("The Number of tails was", tails )

print("\n\nPress the enter key to exit.")

Edited 3 Years Ago by MichaelJPannell

Just mildly more modern ...

''' coinflip102.py
flip a coin 100 times and count heads and tails
'''

import random

# create a 100 count list of random 'head' or 'tail'
mylist = [random.choice(['head', 'tail']) for k in range(100)]

print("The Number of heads was {}".format(mylist.count('head')))
print("The Number of tails was {}".format(mylist.count('tail')))

Edited 3 Years Ago by vegaseat

More concisely the same as vegaseat wrote could be writen:

''' coinflip102.py
flip a coin 100 times and count heads and tails
'''
import random
tails = sum(random.choice(['head', 'tail']) == 'tail' for k in range(100))
print("""The Number of heads was {heads}
The Number of tails was {tails}""".format(tails=tails, heads=100-tails))

Here is a very different solution (the bitCount() function comes from here, it counts the number of bits set in an integer)

import random

def bitCount(int_type):
    count = 0
    while(int_type):
        int_type &= int_type - 1
        count += 1
    return(count)

tails = bitCount(random.getrandbits(100))

:)

It is probably much faster.

Edited 3 Years Ago by Gribouillis

This question has already been answered. Start a new discussion instead.