Using logical operators in an expression

I am trying to understand that bit of code:

s = list()
r = string()
# actual bit of code:
print(s and 'ERROR' or r or 'EMPTY')

What this does:

  • if s is not an empty list, then you must print 'ERROR'
  • else if r is not an empty string you must print r
  • else print 'EMPTY'

I am now trying to understand why this works, and more widely how you can use logical operators in expressions, like in this example.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

x and y is x if it is “false-y” (i.e. 0, False, None, [], '', …), otherwise it is y.
x or y is x if it is “truth-y”, otherwise it is y.

That is, x or y is the same as x if x else y, and x and y the same as x if not x else y.

Method 2

If s is non-empty, s and 'ERROR' produces the truthy value 'ERROR', which short-circuited the rest of the or expression.

If s is empty, s and 'ERROR' produces the false value [], which leads to the evaluation of r to determine if the value of the entire expression is r or EMPTY.

It helps to play with smaller examples using non-Boolean arguments to see how both and and or work.

>>> [] and "ERROR"
[]
>>> ["foo"] and "ERROR"
"ERROR"

It might be clearer to use the conditional expression here:

print("ERROR" if s else (r or "EMPTY"))

or just use a “naive” if statement.

if s:
    print("ERROR")
elif r:
    print(r)
else:
    print("EMPTY")

Method 3

This is a question more focused on logical operators and Short-circuit evaluation
.
Firstly, you need to understand that every variable has a boolean value associated with it.

An empty list is false, a list with a length of 1 or higher is true. This can be checked with the bool() operator:

>>> bool([])
False
>>> bool(['a'])
True

Similarly, an empty string is false and a string of one or more characters is true.

>>> bool('')
False
>>> bool('string')
True

The expression s and 'ERROR' or r or 'EMPTY' is evaluated as follows:

  1. bool(s) and bool('ERROR')
  2. or
  3. bool(r)
  4. or
  5. bool('EMPTY')

When any of these is True, the evaluation ends. It’s merely the order of evaluation.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x