Python Logical Operators

Lesson Contents

One of the Python operator types are Python logical operators. We can combine conditional statements. In the Python comparison operators lesson, we used operators to check if the result is true or false. For example:

The first operator returns true, the second one returns false. What if I want to check both conditions? That’s what we can do with logical operators:

  • AND
  • OR
  • NOT

Let’s try these.

AND

The AND operator returns true when both conditions are true. Otherwise, it returns false.

en
X Y Result
False False False
False True False
True False False
True True True

Here’s an example:

Both conditions are true, so the operator returns true. One more example:

The second condition is false, so the operator returns false as the result. In the two examples above I used numbers but you can also check other items. Here’s an example:

The string “switch” equals “switch” and 10 is greater than 5, so the operator returns “true”.

OR

The OR operator returns true if  at least one of the conditions is true.

en
X Y Result
False False False
False True True
True False True
True True True

Here’s an example:

Both conditions are true, so the operator returns true. One more example:

The first condition is true, the second one is false. Since once condition is true, the operator returns true. When both conditions are false, the operator returns false:

NOT

The NOT operator reverses the result. It returns False when the result is True.

en
X Result
False True
True False

Here’s an example:

Conclusion

You learned how to compare binary values with the Python logical operators:

  • AND: The operator returns True if both conditions are true. Otherwise, it returns False.
  • OR: The operator returns True if either condition is true. If neither condition is true it returns False.
  • NOT: The operator reverses the result. It returns False when the condition is true and returns True when the condition is false.

I hope you enjoyed this lesson. If you have any questions, please leave a comment.


Ask a question or start a discussion by visiting our Community Forum