[Tutor] new user question about while loops

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 27 16:05:10 CEST 2005

> #assigning variables to track the amount of times heads or tails comes up
> heads=0
> tails=1
> AG> Why not make both zero, after all there have been no flips so far!

Hi Alan,

There is confusion here about the role of these variables.  Despite what
the comment says, I assume that 'heads' and 'tails' here are not meant to
count how many times we see heads or tails.

Instead, the code instead seems to say that 0 is an encoding for a coin
flip for heads, and 1 is an encoding for a coin flip for tails.  It's
intrinsically tied to the call to the coin flip itself:


One possible place of confusion, here, is that the program still talks in
the vocabulary of numbers, where it really should be talking in the
vocabulary of coin faces.  Rather than random.randrange(), it is more
appropriate to use random.choice(),

    random.choice([heads, tails])

to explicitely show that we're making a choice among the possible
alternatives of: heads or tails.  The fact that these values are really
integers underneath the surface shouldn't show up in the coin flipping,
and that's why using randrange() is probably not optimal from a human
readability's standpoint here.

(If efficiency is a concern, we probably would optimize this to use
random.randrange() after all.  But if we do so, we should be aware that we
sacrificing the abstraction for performance's sake.)

A problem with encoding something as a number is that it's becomes very
easy to make inadvertant "puns".  0 could stand for a false value, or
heads, or zero coin flips so far, or ... etc.

In summary, when we go back to that code comment:

> #assigning variables to track the amount of times heads or tails comes up
> heads=0
> tails=1

I think the comment is troublesome because it appears to make a bad pun.
I don't think the intent of heads or tails is to count, but rather to
describe the encoding of the concept of a head or tail flip.

Hope this helps!

More information about the Tutor mailing list