Logical Operators

Python Logical Operators  are generally used to compare two or more expressions. Using these operators we can control program flow. The logical operators are frequently used with relational operators.

There are mainly three logical operators which are listed below :-

  • Logical not operator
  • Logical and operator
  • Logical or operator

The logical not Operator is a unary operator and we have already discussed it. not Operator in python

Logical and Operator

The  and keyword is used to perform logical and operation in python. It takes two boolean values as input and returns True if both the values are True, else it will return False, and yes the output will also have a boolean value.

The following is the truth table of and operators in python :-

A B A  and B
False False False
False True False
True False False
True True True

The and operator is generally used to compare two or more expressions.

For example :-

a = 10
b = 20
c = 30
print( a > b and b < c)

The output will be a boolean value False. Let’s simplify the equation first :-

As we can see that a is not greater than b, then the result of the first equation will be False and in the second equation b  is lesser than c then the result will be True.

We know that, if any of the value is False then the whole and operation will become False. So, the output will be :-

False

Logical or Operator

The or keyword is used to perform  Logical  or operation in python.Python logical or operator takes two boolean values as input and return True if any of them is True, else it will return False.

The truth table of following or Operator :-

A B A  or B
False False False
False True True
True False True
True True True

This  logical operation will be used when the operation is expected to happen in the case where even one of the conditions stands true.

Let’s understand this operation through a program :-

a = 10
b = 32
c = 14
print(a == b or b > c)

In the above statement, the result of the first equation will be False as they aren’t equal and the result of the second equation will be True as b  has greater value than c.

As we know that, if any of the values is True in case of or operation then the whole or operation will be True.

So, the output will be :-

True