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:
and operators should be used to check whether all conditions are true or not.
num1 = 4 num2 = 6 if num1 % 2 == 0 and num2 % 2 == 0: print('Both numbers are even.') else: print('Both numbers are not even.')
Both numbers are even.
or operator should be used to check whether at least one condition is true or not.
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.')
At least one of the numbers is even.
not operator is used to reverse boolean value.
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.')
John has passed the exam.
In this article, you learned when and how to use logical operators in python. There are three operators present as logical operators in python:
If you have problems while implementing code, you can ask me through the comment section.