beginner code problem
DaveM
asma61 at dsl.pipex.com
Sat Jun 3 01:56:06 CEST 2006
On Fri, 2 Jun 2006 18:41:53 -0400, RJ <victimorcrime at yahoo.com> wrote:
> I'm trying to teach myself Python (probably running into the old dog
>new tricks issue) and I'm trying to start with the very basics to get a
>handle on them.
>
> I'm trying to write code to get the computer to flip a coin 100 times
>and give me the output of how many times heads and tails. After solving
>a few syntax errors I seem to be stuck in an endless loop and have to
>kill python. A few times I would get it to print 'heads 0 (or 1) times
>and tails 1 (or 0) times' 100 times.
>
>Here's the code I wrote:
>
>import random
>
>flip = random.randrange(2)
>heads = 0
>tails = 0
>count = 0
>
>while count < 100:
>
> if flip == 0:
> heads += 1
>
> else:
> tails += 1
>
>
> count += 1
>
>
>
>print "The coin landed on heads", heads, 'times ' \
> "and tails", tails, 'times'
Several problems here. "flip" is defined just once, so you'll either have
100 heads or tails and your whitespace is all wrong - that's important in
Python. Here's how it should look:
import random
def coinflip():
heads = 0
tails = 0
for goes in range(100):
if random.randrange(2) == 1:
heads += 1
else:
tails += 1
print "heads", heads
print "tails", tails
if __name__ == "__main__":
coinflip()
More information about the Python-list
mailing list