Logical Operators in Python


☞ Non-zero value = True and Zero value = False

☞ Non-empty string(" ") = True and Empty string("") = False

☞ They are binary operators.

☞ Following are the logical operators. To see it precedence, check the precedence table.

not    ➺    logical not
and    ➺    logical and
or     ➺    logical or

Logical NOT (not)

☞ It reverses the result. If experssion is True, then it will convert it into False and vice-versa.

exp1 not exp1
not False True
not True False

Example

x=not 4>3
print(x)
print("----------")
y=not 4
print(y)
print("----------")
z=not 3+4j
print(z)
print("----------")
a=not 0+0j
print(a)
print("----------")
b=not ""
print(b)
print("----------")
c=not "inspirewebsoft"
print(c)

Output

False
----------
False
----------
False
----------
True
----------
True
----------
False

Logical AND (and)

☞If both the expressions will be True, then result will be True.

exp1 exp2 exp1 and exp2
False False False
False True False
True False False
True True True

Example 1 :

x=3>4 and 5>3
print(x)
y=3!=4 and 5>3
print(y)

Output

False
True

Example 2 :

x="web" and "inspire"
print(x)
y="inspire" and "web"
print(y)

Output

inspire
web

Example 3 :

x=51 and 43
print(x)
y=0 and 34
print(y)
z=35 and "inspirewebsoft"
print(z)

Output

43
0
inspirewebsoft

Working with integer values :
If exp1 is false, then result is exp1 otherwise exp2.

Logical OR (or)

☞If any expression will be True, then result will be True.

exp1 exp2 exp1 or exp2
False False False
False True True
True False True
True True True

Example 1

x=3>4 or 5>3
print(x)
y=3!=4 or 5>3
print(y)

Output

True
True

Example 2

x="web" or "inspire"
print(x)
y="inspire" or "web"
print(y)

Output

web
inspire

Example 3

x=51 or 43
print(x)
y=0 or 34
print(y)
z=35 or "inspirewebsoft"
print(z)

Output

51
34
35

Working with integer values :
If exp1 is false, then result is exp2 otherwise exp1.

Note :
Error :- 3 and x=4 , 3 and 5/0
No-error :- 3 and 4>2 , 3 and 3+4 , 3 and 3= =4 , 3 or 5/0 (because if 1st one is true, then it will not check further expressions)