Dive into python and / or fail

I am stuck in this particular example from immersion in python

Example 4.18. When and / or Trick Fails

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

Since a is an empty string that Python considers false in a boolean context, 1 and "evalutes to", and then '' or 'second' evalutes to 'second'. Unfortunately! This is not what you wanted. E-trick, bool and a or b will not work as an expression of C bool? a: b when a is false in the boolean context.

Why does he say that this is not what the user wants, I mean 1, and "will evaluate the value to False, and" "or" b "will evaluate to the" second ", which is fine, what should happen, I don’t I understand why this is wrong? Am I missing something?

+5
source share
4

, .

expr if cond else expr inline Python 2.5 PEP 308;

if cond:
    expr
else:
    expr

, , expr and cond or expr sort-of inline-, boolean true. Python , , , , . "" .

+4

"-" condition ? if-true : if-false . 1 True , , a, b. , , - . Python , 2.5:

true if condition else false
+2

python


x and y or z , python (y if x else z). , , , C x ? y : z.


python wiki., .

+2

, , , 1 " False, " " b " ", , , , ? - ?

, . condition and if-true or if-false - , > 2.5, , condition ? if-true : if-false if-true if condition else if-false.

, if-true - , false ("", [], (), False 0)), , , , , if-true false.

condition and a or b a ("", ), (1) true, 1 and a False, b.

The solution to this problem is to either use Python 2.5+ ( if-true if condition else if-false) syntax or make sure that it is if-truenever false. One way to perform the second - pack if-trueand if-falsein a tuple or a list, as a non-empty iterabel always always:

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

>>> condition and [a] or [b]
['']

>>> (condition and [a] or [b])[0]
''

This is a kind of ugly solution, but it is there if you need to orient old versions of Python.

0
source

All Articles