Python Boolean Operators

Boolean Operators are used to evaluate whether a statement is true or false and return as value either true or false. The Python’s Boolean operators are:

  • and – it returns true if both statements are true.
  • or – it returns true if one of the statements (or both) are true.
  • not – it returns true if the statement is false, otherwise it returns false.

and – Boolean Operator

The and returns true if both statements are true, otherwise it returns false.

myThing = (2 * 7 > 10) and (6 + 6 >= 12)
print(myThing)

The output will be true since both statements are true.

myThing = (2 * 4 > 10) and (6 + 6 >= 12)
print(myThing)

The output will be false since one of the statements (the first one) is false.

You can have more than two statements with the operator and.

myThing = (2 * 7 > 10) and (6 + 6 >= 12) and (4 * 9 > 30)
print(myThing)

All of the statements are true so the output will be true.
You can have any number of statements.

or – Boolean Operator

The or returns true if one of the statements is true, otherwise it returns false.

myThing = (2 * 7 > 10) or (6 + 3 >= 12)
print(myThing)

The output will be true because the first statement is true.

myThing = (2 * 3 > 10) or (6 + 3 >= 12)
print(myThing)

The output will be false because both statement are false.

With or you can also have more than two statements.

myThing = (2 * 3 > 10) or (6 + 6 >= 12) or (4 * 5 > 30)
print(myThing)

The output will be true because the second statement is true.

not – Boolean Operator

The not returns true if the expression it evaluates is false, otherwise it returns true.

myThing = not (2 * 3 > 10) 
print(myThing)

The expression is false so the not operator returns true.

Combining the Boolean Operators

An expression can contain different Boolean operators.

myThing = (2 * 3 > 10) and (6 + 6 >= 12) or (4 * 9 > 30)
print(myThing)

It returns true although the first statement is false. Because the last statement is true, the or operator will return true.

Leave a Reply