Logic

Python allows us to control the flow of our program using logical operators and truth values: True and False.

Operators

Python also allows us to compare attributes of data by using the following:

  • Equality (==)
  • Greater than or equal (>=)
  • Less than or equal (<=)
  • Less than (<)
  • Greater than (>)
  • Not equal (!=)

Double equals is used for checking equality and not used for variable assignment

Here are some examples:

name = "John"
age = 27

name == "James" # equals False
age >= 18 # equals True

22 != '22' # equals True

The last example shows that the both the equality and the not-equality operator checks for types as well. A string will never be ‘equal’ to a number.

Truth Table

There are 2 operators that allow for the combination of these truth values: and and or

These operators will follow the following set of logical rules:

Statement 1 Statement 2 Statement 1 and Statement 2 Statement 1 or Statement 2
T T T T
T F F T
F T F T
F F F F

Logical statements have a similar execution style to that of Math.

  1. Parentheses are computed first.
  2. Proceeds from left to right.
(True and False) or True # equals True