Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operators in Python

Tags:

python

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

like image 839
BoRRis Avatar asked Jun 18 '17 05:06

BoRRis


People also ask

What are the three Python logical operators?

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.

What are logical operators?

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.

Is or a logical operator in Python?

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.


1 Answers

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.

like image 106
hiro protagonist Avatar answered Oct 31 '22 23:10

hiro protagonist