Logical operators in python

Logical operators in python are used to combine conditional statements. Logical operators are used to creating expressions that are used to check single or multiple conditions.

Following operators are present in logical operators:

  1. and operator
  2. or operator
  3. not operator

and operator:

and operators should be used to check whether all conditions are true or not.

Example:

num1 = 4
num2 = 6

if num1 % 2 == 0 and num2 % 2 == 0:
    print('Both numbers are even.')
else:
    print('Both numbers are not even.')

Output:

Both numbers are even.

or operator:

or operator should be used to check whether at least one condition is true or not.

Example:

num1 = 4
num2 = 5

if num1 % 2 == 0 or num2 % 2 == 0:
    print('At least one of the numbers is even.')
else:
    print('Both numbers are not even.')

Output:

At least one of the numbers is even.

not operator:

not operator is used to reverse boolean value.

Example:

In the below example and operator is used, so both conditions have to be true. But has_failed variable has value False, so to convert False value to True not operator is used. So, the result of both conditions is true.

name = 'John'
has_failed = False
if name == 'John' and not has_failed:
    print('John has passed the exam.')

Output:

John has passed the exam.

Conclusion:

In this article, you learned when and how to use logical operators in python. There are three operators present as logical operators in python:

  1. and
  2. or
  3. not

If you have problems while implementing code, you can ask me through the comment section.

See Also:

Arithmetic operators in python

Comparison operators in python

Leave a Reply

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