Python Conditions

Outside Resources:
Corey Schafer – Conditions and Booleans (Youtube)


Python Conditions:

A condition is a statement or expression that is either True or False.

Boolean

Boolean data is either True or False.

For example, you can create a Boolean variable:

x = True

Example Python Conditions:

x < 5
name == “Nancy”
answer == “USA” or answer == “United States”
angle < 45 and velocity > 10
“backpack” in itemlist
response not in [‘yes’, ‘no’]

All of those statements can be evaluated by Python to be either True or False.

Logical Comparison Operators

The following symbols all create Boolean expressions (conditions). That is, any expression using these operators will be calculated by Python, and the result always equals eitherĀ True orĀ False.

Operator What this operator means
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

‘or’ keyword

An expression containing the ‘or’ keyword contains two conditions. If either of those two conditions is True, then the entire expression is True.

Example:

x = 8
x < 10 or x > 100
This condition is True, because the first half of it is true.

‘and’ keyword

If either side of an ‘and’ statement is false, the entire thing is false.

Example:

x = 5

x == 5 and x == 1

The condition is false because the second half is false. Both need to be true in order for the expression to be true.

‘not’ keyword

Any expression with “not” before it will equal the opposite True/False value that it would be otherwise.

not True –> returns False

(True and False) –> returns False
not (True and False) –> returns True