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:

>>> 6 > 3

Will show this output:

True

And:

>>> 5 > 7

Will show this output:

False

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.

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

Here’s an example:

>>> 10 > 5 and 6 > 4

Will show this output:

True

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

>>> 10 > 5 and 10 > 11

Will show this output:

False

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:

>>> "switch" == "switch" and 10 > 5

Will show this output:

True

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:

>>> 1 == 1 or 2 == 2

Will show this output:

True

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

Unlock This Lesson for Free - No Credit Card Needed!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2377 Sign Ups in the last 30 days

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