What Does Python Return When We Return With Logical Operator?
Solution 1:
An expression using and
or or
short-circuits when it can determine that the expression will not evaluate to True or False based on the first operand, and returns the last evaluated value:
>>> 0 and 'string'
0
>>> 1 and 'string'
'string'
>>> 'string' or 10
'string'
>>> '' or 10
10
This 'side-effect' is often used in python code. Note that not
does return a boolean value. See the python documentation on boolean operators for the details.
Solution 2:
An AND statement is equal to the second value if the first value is true. Otherwise it is equal to the first value.
An OR statement is equal to the first value if it is true, otherwise it is equal to the second value.
Note that in Python an object can be evaluated to a boolean value. So "bla" and False
will evaluate to the second value because the first value is true (it is a non-empty string and bool("string") = True
).
This is how boolean statements are evaluated in Python (and multiple other programming languages). For example:
True and False
=False
(equal to second value because the first value is true)False and True
=False
(equal to the first value because the first value is not true)True and True
=True
(equal to the second value because the first value is true)True or False
=True
(equal to the first value because it is true)False or True
=True
(equal to the second value)
Post a Comment for "What Does Python Return When We Return With Logical Operator?"