code doesn't work: question

Geert-Jan Van den Bogaerde gvdbogae at vub.ac.be
Tue Sep 3 06:28:59 EDT 2002


On Tue, 2002-09-03 at 12:03, Ruslan Spivak wrote:
> Hello python-list user,
> 
> I want somebody to explain me why next code doesn't work:
> 
> var = 5
> 
> if (tmp = var) == 5:         # this is the error line
>    print "ok"
> else:
>    print "error"

Python doesn't allow assignment inside expressions, the rationale (from
the Python tutorial at http://www.python.org/doc/current/tut/node7.html
- section 5.5 last sentence): 

"""
Note that in Python, unlike C, assignment cannot occur inside
expressions. C programmers may grumble about this, but it avoids a
common class of problems encountered in C programs: typing = in an
expression when == was intended. 
"""

Given the number of times I've personally made this mistake, I'd agree
with Python's rationale for leaving this out.

As to what to use instead:

>>> var = tmp = 5
>>> if tmp  == 5:         
>>>    print "ok"
>>> else:
>>>    print "error"

Best regards,

Geert-Jan Van den Bogaerde







More information about the Python-list mailing list