954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Coin Flip (Python Newbie)

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

Stephanie953
Light Poster
47 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

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!

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

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

Arrorn
Light Poster
40 posts since Mar 2009
Reputation Points: 7
Solved Threads: 5
 

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 :)

FengG
Newbie Poster
10 posts since Mar 2009
Reputation Points: 16
Solved Threads: 1
 

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

Arrorn
Light Poster
40 posts since Mar 2009
Reputation Points: 7
Solved Threads: 5
 

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.

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

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 :)

Darkangelchick
Light Poster
35 posts since Aug 2008
Reputation Points: 8
Solved Threads: 1
 

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

Stephanie953
Light Poster
47 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

your welcome...
glad to be of some assistance...

Arrorn
Light Poster
40 posts since Mar 2009
Reputation Points: 7
Solved Threads: 5
 

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
 

Oh I didn't notice that problem he had in his code before. Nice catch there woooee!

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

I did get a passing mark and that wasnt a bad code :( but maybe you were right idko and its not a he..i'm a gal :)

Darkangelchick
Light Poster
35 posts since Aug 2008
Reputation Points: 8
Solved Threads: 1
 

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.

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

yeah dw i picked up on that, thanx. My teacher missed it lol.

Darkangelchick
Light Poster
35 posts since Aug 2008
Reputation Points: 8
Solved Threads: 1
 

#Program to flip coin 100 times.

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

while y<=x:
coin=random.randrange(2)+1[/CODE]

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! ")

Attachments coin_flip_100_times.txt (0.33KB)
abuzarbt
Newbie Poster
1 post since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You