Chapter 8: Conditions and Branching
Control the execution flow of your program. Master comparison operators, design conditional pathways using if-elif-else structures, and compound logic via boolean expressions.
Why Do We Need Conditions and Branching?
By default, programming instructions execute sequentially from top to bottom. To build dynamic and smart applications, we need the ability to take different action pathways based on real-time parameters. **Conditional Branching** lets us choose which code path to follow depending on Boolean test conditions.
Let's first explore the mathematical tools used to form comparison conditions in Python.
8.1 Comparison Operations
Comparison operations compare values or operands, returning a boolean value (True or False). They form the fundamental checks for decision-making pathways.
Python provides the following operators:
==: Check if values are equal.!=: Check if values are not equal.>/>=: Greater than / Greater than or equal to.</<=: Less than / Less than or equal to.
Select an operator and move the slider to change variable i. Observe the true (green) and false (red) bounds on the number line in real-time.
Try running this code block to check string comparison properties. String comparison is case-sensitive and evaluates character encodings:
# Comparing Strings
print("AC/DC" == "Michael Jackson") # Evaluates to False
print("AC/DC" != "Michael Jackson") # Evaluates to True
print("a" < "b") # Evaluates to True (alphabetic order)
8.2 & 8.3 Conditional Branching (if, elif, else)
Branching allows your program to run different code blocks depending on input values. Think of an if statement as a locked room: if the condition is True, the lock opens and you run the code inside. If the condition is False, the block is completely skipped.
if: The initial check. Runs ifTrue.elif(else if) : Checked only if preceding conditions areFalse.else: The catch-all path. Runs if all previous checks areFalse.
Simulate a concert ticketing gate. Set the person's age and watch the active logic path and code blocks execute in the flowchart below.
Here is the syntax of the if-elif-else branching statement in Python. Note that colons (:) and indentation spacing are required:
# Let's inspect test grades
score = 83
if score >= 90:
print("Grade: A 🌟")
elif score >= 80:
print("Grade: B 👍")
else:
print("Grade: C - study more!")
8.4 Logical Operators
Logical operations take multiple Boolean values or conditions and output a single Boolean value:
and: ReturnsTrueif both operands areTrue.or: ReturnsTrueif at least one operand isTrue.not: Inverts the boolean operand (turnsTruetoFalse).
Toggle variables A and B to see how they evaluate. Row updates in the truth table dynamically based on your configuration.
| A | B | A and B | A or B |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
Change the release year. The graph below displays evaluations of compound checks: 80s check (via and) vs. Non-80s check (via or).
Try running this code block to verify logic compound bounds in Python:
# Checking year ranges
year = 1983
# Check if year is in the 1980s (inclusive)
if year >= 1980 and year <= 1989:
print("This album was made in the 80's")
# Check if year is NOT in the 1980s (70s or 90s)
if year < 1980 or year >= 1990:
print("This album was made in the 70's or 90's")
Practice Quiz
Test your understanding of Python conditions and branching by answering the questions below.