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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With