Logical operators in Python

Logical operators are used to comparing multiple relational expression. In nesting where one if statement within another if statement because of that in the program, there are multiple statements will execute and code got lengthy. For solving this we can use logical operators by using that we can combine more than one relational expression and according to logical operator return true or false.

Logical operator in Python

They are 3 logical operators in Python –

  1.  And
  2. Or
  3.  Not

 


Contents

  1. AND
  2. OR
  3. NOT

 


1. AND

It needs more than one relational expression and it returns true if all expressions are true and if one of the expression is false then it return false. and is used in those cases where we 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)

When we execute the above program, it will produce the following output –

Number is between 5 and 20
num : 10

2. OR

It also needs more than one relational expressions and it returns true if one of the expressions or both of the expression is true and return false if all expression are false. or is used in those cases where we only need one of the expression is been true.

Syntax –

expression1 or expression2

Example –

num = 10

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

print("num : ",num)

When we execute the above program, it will produce the following output –

In if statement
num : 10

3. NOT

not an operator is used to reverse the logical state of the expression.

Syntax –

not expression1

Example –

num = 10

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

print("num : ",num)

When we execute the above program, it will produce the following output –

In if statement
num : 10

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *