
Understanding 'or' and 'and' Logical Expressions in Python
In Python, logical expressions using the operators 'or' and 'and' don't just return boolean values (True or False). Instead, they actually return one of the objects involved in the expression. Let's dive into how this works.
Logical Expressions with 'or'
When using the 'or' logical operation between two or more objects in Python, it returns the first object that evaluates to True. If none are True, it returns the last object that evaluates to False.
For instance, try typing in this expression:
"" or [] or 0 or ()
All these objects are either False or evaluate to False.
Keep in mind, in Python, zero and all empty sequence types (like lists, tuples, strings, etc.) are considered False. Conversely, any number other than zero and sequence types with at least one element are deemed True.
So, Python will return the last object in the expression, which is:
()
Now, try this expression:
"" or [] or (1,2,3) or 1
Here, there are two items that evaluate to True: the tuple (1,2,3) and the number 1.
Python will return the first one it encounters:
(1,2,3)
But what if you want a boolean result?
To get a boolean value as the result, you need to wrap the entire expression within the bool() function.
bool("" or [] or (1,2,3) or 1))
The bool() function will convert the outcome to a boolean value, returning:
True
Logical Expressions with 'and'
The 'and' operation returns the first object that evaluates to False. If all objects evaluate to True, it returns the last object in the expression.
For example, type in:
"123" and [] and 0 and (1,2,3)
Python will return the first False object it encounters, which is:
[]
Now, try another expression where all objects are True:
"123" and True and 1 and (1,2,3)
Python will return the last True object in the expression, which is:
(1,2,3)
Again, if you want a boolean output, simply wrap the expression in the bool() function.
bool("123" and True and 1 and (1,2,3))
This way, you'll get the boolean value True instead of the tuple (1,2,3)
True