Basic coin flipper program - logical error help
Brian van den Broek
broek at cc.umanitoba.ca
Wed Feb 22 10:11:58 EST 2006
DannyB said unto the world upon 21/02/06 06:14 PM:
> I'm just learning Python. I've created a simple coin flipper program -
> here is the code:
>
> [source]
> #Coin flipper
> import random
>
> heads = 0
> tails = 0
> counter = 0
>
> coin = random.randrange(2)
>
> while (counter < 100):
> if (coin == 0):
> heads += 1
> counter += 1
> else:
> tails += 1
> counter += 1
>
> coin = random.randrange(2)
<snip>
> The program runs - however - it will give me 100 heads OR 100 tails.
> Can someone spot the logic error?
<snip>
Your original question is long since answered. But I've a style point.
As Dennis Lee Bieber pointed out, you don't need all three
accumulators. If you keep to the overall style of your code, you can
avoid repeating yourself as:
while (counter < 100):
counter += 1 # No point in putting this in each branch
coin = random.randrange(2)
if (coin == 0):
heads += 1
else:
tails += 1
For roughly the same style, I'd go with:
heads = 0
count = 100
for i in range(count):
if random.randrange(2):
heads += 1
tails = count - heads
HTH,
Brian vdB
More information about the Python-list
mailing list