Chapter 1 of ?
python 14 min read

Python for Data Science — Chapter 8: Conditions and Branching

Module 3 — Control Flow

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.
Comparison Operations & Number Line Explorer

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.

Interactive Evaluation ConsoleBoolean Result
Loading comparison...

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 if True.
  • elif (else if) : Checked only if preceding conditions are False.
  • else : The catch-all path. Runs if all previous checks are False.
Concert Attendance Flowchart Explorer

Simulate a concert ticketing gate. Set the person's age and watch the active logic path and code blocks execute in the flowchart below.

START (Age Input) age >= 19? True AC/DC Concert (Entrance Blue Box) False age == 18? True Pink Floyd Concert (Entrance Pink Box) False Meat Loaf Concert (Entrance Purple Box)
Executed Code Output PreviewPython Console Output
Loading execution flow...

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 : Returns True if both operands are True.
  • or : Returns True if at least one operand is True.
  • not : Inverts the boolean operand (turns True to False).
Logical Operators Truth Table & Sandbox

Toggle variables A and B to see how they evaluate. Row updates in the truth table dynamically based on your configuration.

Sandbox Inputs
Boolean A:
Boolean B:
A and B: False
A or B: True
not A: False
Truth Table
A B A and B A or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse
Album Era Filter (Range Checking)

Change the release year. The graph below displays evaluations of compound checks: 80s check (via and) vs. Non-80s check (via or).

Logic Check ConsoleEvaluated Code Output
Loading logic evaluation...

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.

Test Your Understanding

Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *