Jesse's Blog » 日志 » A gotcha with *if* in Python
A gotcha with *if* in Python
Jesse 发表于 2008-06-12 17:44:56
(1).
I was to compare two tuples:
if tuple1 > tuple2:
....
(2).
But these tuples contained expressions as elements, say, tuple1 = (a,b), tuple2 = (s,t); b and t were quite long.
(3).
So I wrote the above code as following since it can't fit in one single line.
if (a, b >
s, t):
....
Then the monster came, things always went wrong and I could find the bug nowhere...
(4).
Accidentally, for another reason, I added a temporary variable to store b and t. The statement was much shorter now, and one line was OK.
The code ended like:
if a, b > s, t:
....
Python told me that I can't write things like that, so I need two pairs of parentheses:
if (a,b) > (s,t):
Then, suddenly, everything went all right..
================
In Python, if we are to compare two pairs of things (in the form of tuples or lists), parentheses are required.
My first attempt is just like:
if (a, b > s, t):
which is the same as:
if a, (b > s), t:
It is obviously wrong.
Jesse
I was to compare two tuples:
if tuple1 > tuple2:
....
(2).
But these tuples contained expressions as elements, say, tuple1 = (a,b), tuple2 = (s,t); b and t were quite long.
(3).
So I wrote the above code as following since it can't fit in one single line.
if (a, b >
s, t):
....
Then the monster came, things always went wrong and I could find the bug nowhere...
(4).
Accidentally, for another reason, I added a temporary variable to store b and t. The statement was much shorter now, and one line was OK.
The code ended like:
if a, b > s, t:
....
Python told me that I can't write things like that, so I need two pairs of parentheses:
if (a,b) > (s,t):
Then, suddenly, everything went all right..
================
In Python, if we are to compare two pairs of things (in the form of tuples or lists), parentheses are required.
My first attempt is just like:
if (a, b > s, t):
which is the same as:
if a, (b > s), t:
It is obviously wrong.
Jesse
收藏:
QQ书签
del.icio.us
订阅:
Google
抓虾
