Dremendo Tag Line

Logical Operators in Python

Operators in Python

In this lesson, we will learn what is the Logical Operators and how it works in Python programming with some examples.

What is Logical Operators

Logical operators in Python are used to evaluate two or more conditions. They allow a program to make a decision based on multiple conditions. If the result of the logical operator is true then 1 is returned otherwise 0 is returned.

There are 3 types of logical operators in Python and they are:

  • and
  • or
  • not

Now let's see the examples of all the logical operators one by one for more understanding.

video-poster

and Operator

and operator is used to check if two or more given conditions are true or not. The output of and operator is True only if all the given conditions are correct otherwise the output will be False if any one of the given conditions is wrong.

Example

x=15
y=2
z=6
k=25
a=x>5 and y<6 and k>=25     # output of a is True
b=x>y and k<25              # output of b is False

In the example above the output of a is True because all the three given conditions x>5, y<6 and k>=25 are correct (true). On the other hand the output of b is False because out of the two given conditions x>y and k<25 the second condition k<25 is wrong (false).

or Operator

or operator is used to check if any one of the given conditions is true or not. The output of or operator is True if at least any one of the given conditions is correct otherwise the output will be False only if all the given conditions are wrong.

Example

x=15
y=2
z=6
k=25
a=x<5 or y<6 or k>=25     # output of a is True
b=x<y or k<25             # output of b is False

In the example above the output of a is True because out of the three given conditions x<5, y<6 and k>=25 the second condition is correct (true). On the other hand the output of b is False because out of the two given conditions x<y and k<25 both of them are wrong (false).

not Operator

not operator negates the value of the condition. If the condition is false then the output of not operator becomes True. If the condition is true then the output of not operator becomes False.

Example

x=15
y=10
a=not(x>5)     # output of a is False
b=not(y<5)     # output of b is True

In the example above the output of a is False because the given condition x>5 is correct (true) so not operator changed the output from True to False. On the other hand the output of b is False because the given condition y<5 is wrong (false) so not operator changed the output from False to True.

Test Your Knowledge


You Scored :

Percentage :