Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is the construct x = (Condition and A or B) used?

One of the answers to this question is

print len(s)>5 and 'y' or 'n'
print(len(s)>5 and 'y' or 'n') #python3

if the length of s > 5, then 'y' is printed otherwise 'n' is. Please explain how/why this works. Thanks.

I understand that this is not a recommended approach but I'd like to understand why it works.

like image 765
Disnami Avatar asked Jul 15 '12 13:07

Disnami


1 Answers

This is an old-fashioned hack. The new way is:

print 'y' if len(s) > 5 else 'n'

The reason it works is because "A and B" will evaluate A, and if it is true, will evaluate to B. But if A is false, it doesn't need to evaluate B. Similarly, "C or D" will evaluate C, and if it is false, will continue on to evaluate as D.

So "A and B or C" is the same as "(A and B) or C". If A is true, it will evaluate B. If A is false, then "(A and B)" is false, so it will evaluate C.

As Voo points out in the comments, the value of A need not be True or False, but any expression, and will be interpreted as a boolean by Python's rules (0, None, and empty containers are false, everything else is true).

like image 133
Ned Batchelder Avatar answered Oct 17 '22 06:10

Ned Batchelder