Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

Logical operators in Python

While reading the Logical operators in python i came across with expressions :

  5 and 1 

output : 1

  5 or 1 

output : 5

Can anyone explain how is this working ?
I know that the operands of the logical operators are Boolean

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...