Boolean operators in Python

When reading logical operators in python, I came across expressions:

  5 and 1 

output: 1

  5 or 1 

output: 5

Can anyone explain how this works?
I know that operands of logical operators are Boolean

+4
source share
4 answers

which 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 circuits (for example, orwill not evaluate yif xtrue).

the documentation also states that is false ( False, 0, None, empty sequences / matching ...) - everything else is considered to be true.

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]

, : ( IndexError) .

, . python booleans ( 2 : True False, int). python , . bool function .


, , python. , , . english.stackexchange.com, wikipedia.

+7

.

and True, . a False, False, .

>>> 1 and 2
2
>>> 2 and 1
1
>>> 1 and 2 and 3
3
>>> 1 and 0 and 2
0
>>> 0 and 1 and 2
0

or , True, , True. , -, True, True, .

>>> 0 or 1
1
>>> 1 or 0
1
>>> 1 or 2
1
>>> 2 or 1
2
>>> 0 or 0 or 1
1
>>> 0 or 1 or 2
1
+1

. , "a" "b", " ", python . , "a" "b", "a" , python , .

0

, , , , . , .

, , , .

This is an example of lazy appreciation.

0
source

Source: https://habr.com/ru/post/1679542/


All Articles