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.

They are 3 logical operators in Python –
  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 = 15

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 : 15

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 = 12

if num > 6 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 : 12

3. NOT

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

Syntax –

not expression1

Example –

num = 15

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

print("num : ",num)
 
When we execute the above program, it will produce the following output –

In if statement
num : 15

No comments

Powered by Blogger.