[Tutor] while loops

Jay Loden python at jayloden.com
Mon Aug 8 15:58:38 CEST 2005


> coin = random.randrange(2)

That's the problem there...you've got coin assigned outside the while loop, so 
it is assigned 0 or 1 once, before the loop, and then you're running 100 
checks on the same value. 

If you move 
> coin = random.randrange(2)

to inside the while loop before the if statement, you'll get the result you 
want. 

-Jay


On Monday 08 August 2005 5:41 pm, Will Harris wrote:
> I am working my way through "python programming for the absolute beginner"
> and one of the challenges is to create a program that will flip a coin 100
> times and tell you how many of each it did. Now I have it flipping the
> coin, but when I try to do this 100 times I end up with it running through
> 100 times, but always the same result comes back. It will either be 100
> heads, or 100 tails. I have tried if statements and while loops and both
> seem to give me all or nothing. I am just looking for a hint at the
> direction to look of adjust to get the code below working not really the
> solution. Thanks in advanced for any tips.
>
> #!/usr/bin/python
> import random
>
> coin = random.randrange(2)
>
> count = 0
> head_count = 0
> tail_count = 0
>
> while (count != 100):
>         if coin == 0:
>                 print "You got Heads!"
>                 head_count = head_count + 1
>                 count = count + 1
>         else:
>                 print "You got Tails!"
>                 tail_count = tail_count + 1
>                 count = count + 1
>
> print "Out of", count, "you flipped", head_count, "heads and ", tail_count,
> "tails"
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list