[Edu-sig] Interesting "gotcha"

Michael H. Goldwasser goldwamh at slu.edu
Tue Mar 29 07:06:50 CEST 2011


To start a new thread, I'm always trying to keep a list of some common
"gotchas" that beginning students run across when using Python, or
things that teachers should keep in mind when teaching with the
language. I have in mind commands that do not generate runtime errors,
but are likely to lead to logical errors that are not apparent to
students, and most of these are legal due to the very flexible nature
of the Python language.  Some classicss are

data.sort                  # no-op

data = data.sort()         # bye-bye data

result = result.upper      # probably not what you expect

if answer.isupper:         # always true ("but I entered a lowercase answer")


This semester, I ran across a new one that took me quite some time to
figure out what was happening.  This started with a habit that too
many students have of wanting to compare boolean values to True/False
literals, rather than just using the boolean as a condition.  That is,
students seem drawn to the syntax

  if answer.isupper() == True:

rather than the preferred

  if answer.isupper():

These complaints are more of style than substance, as the two
versions are logically equivalent.   But then a student came to me
with code that wasn't behaving.  The syntax they used was something
akin to 


  if x > y == True:

however the condition was not being triggered, even when we verified
that x was indeed greater than y. You can try this out with explicit
values as follows.

>>> if 5 > 4 == True:
...     print "Good"
>>>

You will find that the body is not executed.  More directly, you can
look at the conditional value directly as

>>> 5 > 4
True
>>> 5 > 4 == True
False

This baffled me for an hour before finally seeing what was happening.
I'll leave this as a puzzle for readers (many of whom I'm sure will be
quicker than I was to see the solution).  For those who give up, I
offer the following link as a spoiler.
http://docs.python.org/reference/expressions.html#comparisons

With regard,
Michael

+-----------------------------------------------
| Michael H. Goldwasser, Ph.D.
| Associate Professor
| Director of Computer Science
| Dept. Mathematics and Computer Science
| Saint Louis University
| 220 North Grand Blvd.
| St. Louis, MO 63103-2007
|
| Office: Ritter Hall 108
| Email:  goldwamh at slu.edu
| URL:    http://cs.slu.edu/~goldwasser
| Phone:  (314) 977-7039
| Fax:    (314) 977-1452



More information about the Edu-sig mailing list