While reading about logical operators in python, I came across the following expressions:
5 and 1
output: 1
5 or 1
output: 5
Can anyone explain how this is working?
I know that the operands of the logical operators are Boolean
There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False . These operators are and , or , and not and are defined in the table below.
A logical operator is a symbol or word used to connect two or more expressions such that the value of the compound expression produced depends only on that of the original expressions and on the meaning of the operator. Common logical operators include AND, OR, and NOT.
There are three Boolean operators in Python: and , or , and not . With them, you can test conditions and decide which execution path your programs will take. In this tutorial, you'll learn about the Python or operator and how to use it.
that is well documented:
x or y if x is false, then y, else x
x and y if x is false, then x, else y
both short-circuit (e.g. or
will not evaluate y
if x
is truthy).
the documentation also states what is considered falsy (False
, 0
, None
, empty sequences/mappings, ...) - everything else is considered truthy.
a few examples:
7 and 'a' # -> 'a'
[] or None # -> None
{'a': 1} or 'abc'[5] # -> {'a': 1}; no IndexError raised from 'abc'[5]
False and 'abc'[5] # -> False; no IndexError raised from 'abc'[5]
note how the last two show the short-circuit behavior: the second statement (that would raise an IndexError
) is not executed.
your statement that the operands are boolean is a bit moot. python does have booleans (actually just 2 of them: True
and False
; they are subtypes of int). but logical operations in python just check if operands are truthy or falsy. the bool
function is not called on the operands.
the terms truthy and falsy seem not to be used in the official python documentation. but books teaching python and the community here do use these terms. there is a discussion about the terms on english.stackexchange.com and also a mention on wikipedia.
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