Basic coin flipper program - logical error help
John McMonagle
johnmc at velseis.com.au
Tue Feb 21 19:33:11 EST 2006
On Tue, 2006-02-21 at 16:14 -0800, DannyB wrote:
> 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)
>
>
> print "\nThe coin landed on heads", heads, "times."
> print "\nThe coin landed on tails", tails, "times."
> [/source]
>
> <<<I'm sure the [source] tags don't work - I through them in there
> anyway.>>>
>
> The program runs - however - it will give me 100 heads OR 100 tails.
> Can someone spot the logic error?
Yes. Put coin = random.randrange(2) inside the while loop.
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)
print "\nThe coin landed on heads", heads, "times."
print "\nThe coin landed on tails", tails, "times."
--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.
More information about the Python-list
mailing list