Logic Comparisons

Boolean operators

There are three basic boolean operators in Python.

  • andTrue if left and right value are both True or both False
  • orTrue if either left, right or both are True1
  • not – gives the opposite value of the boolean to the right, i.e. not True == False

1 If the first condition is met, then the second condition will not be tested.

Boolean comparisons

  • == – equal (not recommended for use with float values)
  • != – not equal
  • < – less than
  • <= – less than or equal to
  • > – greater than
  • >= – greater than or equal to

If/Else

if statements allow one to execute a piece of code only if a certain condition is met.

if 3 > 4:
    print('Wow, 3 > 4 is True!')

In the above example, a print() statement is nested (indented underneath) within an if statement. It will only run if its boolean test returns True. However, as 3 > 4 is a false statement, the print() statement will not run.

Conditional logic can also be chained together using if, elif, and else statements (if, else if, and else in other languages).

An elif is a type of if statement that only runs where the previous if or elif test was False. This provides an opportunity to handle a variety of cases using different chained tests.

Finally, an else statement – placed at the end of an if/elif chain – executes its code where all previous tests have returned False. An else statement is generally used to catch all cases not handled with earlier logic tests.