Hey, I just started learning Python yesterday and I got to the end of a chapter on Branching and While Loops...which lead me to a "challenge"...basically it gives me the description of a program and I have to write it. This program flips a coin 100 times and then gives the number of tails and heads. Heres what I have so far:

import random
coin = random.randrange(2) + 1
amount = 100
heads = 1
tails = 2

while amount > 0:
    heads += 1
    tails += 2

raw_input("\n\nEnter Exits")

I want amount to go down by one each time its flipped and then it would stop at 0. I still need to add a raw_input like "Hit enter to start flipping the coin"...but I'm waiting till I get this part done first.

Thanks for any input.

def flipcoin(times)
    from random import randint
    start = input("Press enter to start flipping")
    heads, tails = 0, 0
    for i in range(times):
        if randint(0, 1) == 1: heads += 1
        else: tails += 1
    print("Heads:", heads, "   Tails:", tails)
    if heads > tails: print("Heads won!")
    elif heads == tails: print("tie.")
    else: print("Tails won!")

That should work..

Note:
the reason I used input, not raw_input is because I use python 3, which fixes the raw_input/input problem, just making input do the same as raw_input used to. If you're not using python 3, use raw_input.

Thanks, I havent learned some of this stuff yet...but I think I understand it all. Going to start making sense of it right now ;-)

You can go with a while loop, but you have to add one to heads if it's a head, similarly with tail, also you have to deduct one from the amount within the loop. Look it over, it will make sense ...

import random

amount = 100
heads = 0
tails = 0

while amount > 0:
    coin = random.choice(('head', 'tail'))
    if coin == 'head':
        heads += 1
    else:
        tails += 1
    amount -= 1

print "Heads =", heads, "  Tails =", tails

raw_input("\n\nPress Enter to Exit ")

You can go with a while loop, but you have to add one to heads if it's a head, similarly with tail, also you have to deduct one from the amount within the loop. Look it over, it will make sense ...

import random

amount = 100
heads = 0
tails = 0
countHash = {'head':0,'tail':0}

while amount > 0:
    coin = random.choice(('head', 'tail'))
#    if coin == 'head':
#        heads += 1
#    else:
#        tails += 1
    countHash[coin] += 1
    amount -= 1

#print "Heads =", heads, "  Tails =", tails
print "Heads =", countHash['head'],"Tails=",countHash['tails']

raw_input("\n\nPress Enter to Exit ")

dict maybe more elegant

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