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

Zachary Ware zachary.ware+pytut at gmail.com
Wed Feb 12 20:13:33 CET 2014


Hi Marc,

On Wed, Feb 12, 2014 at 9:25 AM, Marc Eymard <marc_eymard at hotmail.com> wrote:
> Hello there,
>
> I want to emulate a coin flip and count how many heads and tails when
> flipping it a hundred times.
>
> I first coded coinflip_WRONG.py with "count_flips += 1" statement within the
> if/else block.
> When running it, either returned values are wrong or the script seems to
> enter in an infinite loop showing no return values at all.
>
> coinflip.py is a corrected version I worked out myself. I moved
> "count_flips+= 1" out of if/else block and inserted it before if/else.
>
> 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.
>
> Can somebody explain the reason of the bug.

The problem is that conflip_WRONG.py isn't doing what you think it's
doing :).  In particular, lines 23 and 24:

"""
    else: count_tails += 1
    count_flips += 1
"""

While including a statement on the same line after "else:" is legal,
it restricts you to only one statement in the block.  So if we move
that statement off of that line and into the block, we have this:

"""
    else:
        count_tails += 1
    count_flips += 1
"""

I think you may be able to see what's going on from here, but to spell
it out: instead of being executed in the else block, "count_flips +=1"
is being executed unconditionally.  Since there's also a "count_flips
+= 1" in the "if coin_side == 1" block, count_flips is incremented
twice when coin_side == 1, and once otherwise.  Since your loop
condition is "coin_flips != 100", when you reach the point of
coin_flips == 99 and coin_side comes up 1, coin_flips will be
incremented to 101, and the loop condition will still be
satisfied--hence your infinite loop.

Having "count_flips += 1" outside the if/else construct is better
code, since you want it to be done exactly once each time through the
loop no matter what, and reduces repetition.  There are several other
ways to improve your code as well, but they'll come with experience
(or from asking :)).

Hope this helps,

-- 
Zach


More information about the Tutor mailing list