[Tutor] Beginner - explaining 'Flip a coin' bug

Steven D'Aprano steve at pearwood.info
Wed Feb 12 22:06:06 CET 2014


On Wed, Feb 12, 2014 at 03:25:22PM +0000, Marc Eymard wrote:

> However, I still don't understand the bug since, in my understanding, 
> both files are incrementing variable count_flips each time until the 
> loop becomes false.

The problem with the "wrong" file is that it increments the count_flaps 
variable too many times.

You have code:


while count_flips != 100:
    coin_side = random.randint(1,2)
    #count_flips += 1
    if coin_side == 1:
        count_heads += 1
        count_flips += 1
    else: count_tails += 1
    count_flips += 1


where I have added the annotations A and B. So you can see that each 
time you flip Heads, the "if" statement runs the indented block with two 
lines:

    if coin_side == 1:
        count_heads += 1
        count_flips += 1

then jumps past the "else" block with a single in-line statement:

    else: count_tails += 1

and continues running the code past the if...else block, but still 
inside the while block past:

    count_flips += 1

So every time you toss a Head, the number of flips is incremented TWICE 
instead of once. That means that sometimes you'll have fewer than 100 
coin tosses, as seen by adding the number of Heads and Tails, e.g. you 
might have 30 Tails and 35 Heads (each Tail counts once, and each Head 
counts twice, giving 100 mis-counted flips).

But occasionally, if you happen to toss Heads when the count is at 99, 
you'll jump to 101 skipping over 100, and the while-loop then will loop 
forever.

In my next email, I'll explain how to better improve the code.


-- 
Steven


More information about the Tutor mailing list