As mentioned earlier in this unit, states or conditions are incredibly important for dictating the flow of Python programs.
A choose-your-own adventure book may tell a reader, "go to page 53 if you want to hitchhike to Los Angeles or go to page 27 if you want to pay for a bus ticket to Los Angeles". In Python, we can express similar logic, such as "execute this block of code if a certain condition is met, otherwise execute this other block of code." Some more specific examples:
- "If the promo code is valid, add a 20% discount for the shopper. Otherwise, charge them full price."
- "If the user is not logged in, show a login button. Otherwise, show a logout button."
- "If a student is struggling with a concept in OpenClass, show them easier questions. Otherwise, move them on with the assignment."
The above are all examples of if statements, which we will cover in more detail in the next lesson. But before understanding if statements, we must understand the conditional statements that go into them.
Let's break it down
Consider the following statement: "If a number is odd, print it. Otherwise, add 1 to it." This is valid logic that could go into a Python program. But let's break this problem down even further.
The first thing that we want to know is, "is the number odd?" This question can have one of two possible answers: "yes" or "no".
And that's what a boolean value is. A boolean can hold a value of True
or False
. We can then use these booleans to help dictate the flow of our programs.
Note: Proper capitalization is important for keywords in Python! True
and False
are boolean values, whereas true
and false
have no special significance in Python.
What do booleans look like?
The keywords True
and False
are used to represent boolean values in Python. As an example:
c
is False
because 15
is NOT greater than 20
. 15 > 20
evaluates as False
!
The other comparison operators in Python include the following:
Operator | Meaning |
---|---|
a == b |
Are a and b equal? |
a != b |
Are a and b NOT equal? |
a > b |
Is a greater than b ? |
a < b |
Is a less than b ? |
a >= b |
Is a greater than or equal to b ? |
a <= b |
Is a less than or equal to b ? |
Logical operators
Now that we're able to set boolean variables as True
or False
via comparison operators, we can now get fancier with them via logical operators. For instance, what if we want to know if a number is both odd AND greater than 100? We can combine two conditional statements via the and
operator, such as:
'>
Lastly, we can flip-flop True
to False
and False
to True
via the unary not
operator. (Unary means this operator performs its operation on just one conditional statement. Conversely, and
and or
have a left side and a right side operation, and are thus, binary operators.)
Here's an example:
Let's try some examples
Consider the following code. Predict what each of the print statements will output.
Answers: a. True, b. False, c. False, d. False, e. True, f. True