Logical Operators in Python

Logical operators are used to perform logical operations of given expressions (relational expressions) or variables.

There are three logical operators available in Python. Let’s discuss one by one.




Logical or operator

If one of the operands or expressions is true, it will return 1.

If all of them are false, it will return 0.

A B A or B Example
0 0 0 (5 > 10) or (5 < 4)         Both expressions are false. so, logical 'or' output will be 0
0 1 1 (10 > 20) or (10 < 20)    First expression is false and second one is true. so, logical 'or' output will be 1
1 0 1 (10 < 20) or (10 > 100)   First expression is true and second one is false. so, logical 'or' output will be 1
1 1 1 (10 < 20) or (10 < 100)   Both expressions are true. so, logical 'or' output will be 1




Logical and operator

If both left and right operands or expressions are true, it will return true. Otherwise, it will return false.

Note, non-zero value operands are considered as true.

A B A and B Example
0 0 0 (5 > 10) and (5 < 4)         Both expressions are false. so, logical 'and' output will be 0
0 1 0 (10 > 20) and (10 < 20)    First expression is false and second one is true. so, logical 'and' output will be 0
1 0 0 (10 < 20) and (10 > 100)   First expression is true and second one is false. so, logical 'and' output will be 0
1 1 1 (10 < 20) and (10 < 100)   Both expressions are true. so, logical 'and' output will be 1





Logical not operator

Logical not operator is used to inverse the current decision. Say, if current state is true, Logical not operator will make it as false.

A not(A) Example
0 1 not(100 < 10)   100 is greater than 10. So, it will return false.
not(false) ==> true
1 0 not(10 < 100)   10 is less than 100. So, it will return true.
not(true) ==> false




Sample Program


Example

#python logical operators

a = 5
b = 10
 
ret = ( (a <= b) or (a != b) ) 
# 5 <= 10 ==> true. 5 != 10 ==> true. So, true(1) or true(1) will return true.
print("Return value of first expression is ", ret)
 
ret = ( ( a < b) and (a == b ) )
# 5 < 10 ==>true. 5 == 10 ==> false. So, true(1) and false(0) will return false.
print("Return value of second expression is ", ret)
 
ret = not ( ( a < b) and (a == b ) ) 
#   we have used the same expression here.
#   And its result was false.
#   So not(false) will be true.
print("Return value of third expression is ", ret)


Topics You Might Like