This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Logical operators

Logical operators

face Josiah Wang

So far, we have covered the following operators in Python:

  • the assignment operator =
  • arithmetic operators +, -, *, /, //, %, **
  • logical operators >, <, ==, !=, >=, <=

Also remember that the type of the operands dictates what the operators do (operator overloading), e.g. comparing or adding two strings.

Now, here is yet another set of Python operators to add to your knowledge base, called logical operators.

  • not
  • and
  • or

These are actually quite self-explanatory. Example usage:

  • not x < 3
  • x < 3 and y == 2
  • x <= 5 or x > 20
  • x < 2 or x > 5 and y!= 2
  • True and False

These logical operators can also be used as part of the condition in if and while statements:

if (num1 == 1 or num1 == 11) and num2 == 10:
    print("Perfect combination!")
else:
    print("You lose!")