Alright, so Python still surprises me every now and then. Here's a fun one that I stumbled across by accident today:
>>> 0 == 0 == 0
True
>>> 0 == 0 == 1
False
>>> 0 == 1 == 0
False
>>> 0 == 1 == 1
False
>>> 1 == 0 == 0
False
>>> 1 == 0 == 1
False
>>> 1 == 1 == 0
False
>>> 1 == 1 == 1
True
Did you expect that? I sure didn't. But I guess Python is famous for "special casing" its operators to avoid confusing beginners in several places. So they end up confusing people who know lots of other languages instead. Here's what I would have expected to happen (but Python only does this with explicit parenthesis):
>>> (0 == 0) == 1
True
Good times! :-D BTW, in case you were wondering, another place where Python does the "right thing" despite what you may expect coming from C and similar languages:
14 < i < 99 actually does the proper range check, and not by accident either.
No comments:
Post a Comment