Different types of Logical operators in Python

Logical operators are used to combine conditional statements and perform logical operations. It plays a crucial role in decision-making and control flow in a program.

If in your program there is a nested if statement to execute a block of code, it works but it also makes the code lengthy.

For solving this you can use logical operators by using that combine more than one relational expression and according to the logical operator return true or false.

They are 3 logical operators in Python –

  1.  And
  2. Or
  3.  Not

Different types of Logical operators in Python


Contents

  1. AND
  2. OR
  3. NOT
  4. Conclusion

1. AND

It needs more than one relational expression and it returns true if all expressions are true otherwise, it returns false.

and is used in those cases where need all expressions must be true.

Syntax –

expression1 and expression2

Example –

num = 10

if num > 5 and num < 20
   print("Number is between 5 and 20")

print("num : ",num)

Output

Number is between 5 and 20
num : 10

2. OR

It also needs more than one relational expression and it returns true if one of the expressions or both of the expression is true and return false if all expression is false.

or is used in those cases where need one of the expression must be true.

Syntax –

expression1 or expression2

Example –

num = 10

if num > 5 or num < 20
   print("In if statement")

print("num : ",num)

Output

In if statement
num : 10

3. NOT

not operator is used to reverse the logical state of the expression. If a condition is returning false with not operator then code will be executed. Similarly, if it return true then the block of code will not execute.

Syntax –

not expression1

Example –

num = 10

if not num < 5
   print("In if statement")

print("num : ",num)

Output

In if statement
num : 10

4. Conclusion

Using these operators you can easily replace your multiple if statement code in your program. You can also use all 3 operators in a single condition.

Choose an operator for creating an expression according to the requirement.

If you found this tutorial helpful then don't forget to share.

Leave a Comment