Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dive into python and-or fail

Tags:

python

I am stuck at this particular example from dive into python

Example 4.18. When the and−or Trick Fails

>>>>a = ""
>>>>b = "second"
>>>1 and a or b
>>>>'second'

Since a is an empty string, which Python considers false in a boolean context, 1 and '' evalutes to '', and then '' or 'second' evalutes to 'second'. Oops! That's not what you wanted. The and−or trick, bool and a or b, will not work like the C expression bool ? a : b when a is false in a boolean context.

Why does it says it isn't what the user wants, I mean 1 and "" would evaluate to False, while "" or b will evaluate to "second", that's perfectly what should happen, I don't understand why is it wrong?am I missing something?

like image 538
Kartik Anand Avatar asked May 24 '12 16:05

Kartik Anand


1 Answers

No, you're not missing something.

The expr if cond else expr inline conditional was introduced to Python 2.5 in PEP 308; before that, conditionals had to be of the full form

if cond:
    expr
else:
    expr

However, people noticed that expr and cond or expr sort-of worked as an inline conditional, as long as the first expressions happened to evaluate to boolean true. As most things in Python are true, this syntax generally tended to work -- and then, of course, sometimes fail. This was in fact the motivation for adding the "proper" inline conditional.

like image 196
Katriel Avatar answered Sep 24 '22 19:09

Katriel