# 5.7. Truth Tables¶

Truth tables help us understand how logical operators work by showing all of the possible return values. Let’s look at the truth table for `and`, which assumes we have two boolean expressions, `A` and `B`.

Example

Truth Table for `and`

A

B

A `and` B

`True`

`True`

`True`

`True`

`False`

`False`

`False`

`True`

`False`

`False`

`False`

`False`

Consider the first row of the table. This row states that if A is true and B is true, then `A and B` is true. The two middle rows show that if either A or B is false, then `A and B` is false. Finally, if both A and B are false, then `A and B` is false.

Try It!

Now take a look at the truth table for `or`.

1. PREDICT whether `A or B` should be `True` or `False` for each row.

Truth Table for `or`

A

B

A `or` B

`True`

`True`

True

`True`

`False`

True

`False`

`True`

True

`False`

`False`

False

## 5.7.1. Order of Operations¶

We now have a lot of operators in our toolkit, so it is important to understand how they relate to each other. Which operators get done first?

Python always performs operations in a specific order:

1. It does all math calculations first.

2. Next, it evaluates all comparisons as `True` or `False`.

3. Next, it applies all `not` operators.

4. Finally, it evaluates `and` and `or` operations.

Example

The expression `x * 5 >= 10 and y - 6 <= 20` will be completed in this order:

1. `x * 5` is calculated, then `y - 6`.

2. The `>=` comparison is evaluated as `True` or `False`.

3. The `<=` comparison is evaluated as `True` or `False`.

4. The `and` operator is evaluated last.

Let’s say `x = 2` and `y = 46`. Here we step through each stage of the evaluation:

Operator Order on: `x * 5 >= 10 and y - 6 <= 20`

Action

Result

Plug in the values into the expression

`2 * 5 >= 10 and 46 - 6 <= 20`

`x * 5` is calculated, then `y - 6`

`10 >= 10 and 40 <= 20`

The `>=` comparison is evaluated as `True` or `False`

`True and 40 <= 20`

The `<=` comparison is evaluated as `True` or `False`

`True and False`

The `and` operator is evaluated last

`False`

### 5.7.1.1. Table of Operator Order¶

The following table lists operators in order of importance, from highest (applied first) to lowest (applied last).

Operator Order

Level

Category

Operators

(Highest)

Parentheses

`()`

Exponent

`**` (For example: `2**3`)

Multiplication and Division

`*  /  //  %`

`+  -`

Comparison

`==  !=  <=  >=  >  <`

Logical

`not`

Logical

`and`

(Lowest)

Logical

`or`

Tip

Using parentheses is not always necessary, but they make a BIG difference when someone else reads your code. As a best practice, use parentheses to make your code easier to read:

`x * 5 >= 10 and y - 6 <= 20`

vs.

`(x * 5 >= 10) and (y - 6 <= 20)`

Assume we have 3 boolean expressions (A, B, and C). Which combinations of values (A/B/C) will make the expression `A or B and C` evaluate to `True`? Click ALL that apply.