Browse Python Topics ▼
Pick a Web Framework

Conditions and Branching

📂 Control Flow 📘 Lesson 13 of 57

Direct program execution dynamically using if, elif, and else statements, boolean truthiness, nested logic, and ternary conditional expressions.

Up until this point, your programs have run like a straight road: line 1 executed, followed by line 2, line 3, and so on until the end of the file.

However, real software is rarely a straight line. Software must respond dynamically to changing conditions:

  • If a password is correct, log the user into their dashboard; otherwise, display an error message.
  • If an item is in stock, process the credit card charge; else, notify the supplier.
  • If an enemy’s health hits zero, award points to the player.

In programming, this decision-making power is called Control Flow or Branching. In Python, you control branching using if, elif, and else.


1. The Basic if Statement

The if statement is the foundation of decision-making. It evaluates an expression using operators; if that expression evaluates to True, the indented code block executes. If it evaluates to False, Python skips the block entirely:

temperature = 85

if temperature > 80:
    # This block only runs if temperature > 80 is True
    print("It is a warm day outside!")
    print("Remember to drink plenty of water.")

print("Weather check complete.")

Output:

It is a warm day outside!
Remember to drink plenty of water.
Weather check complete.

The Two Syntax Essentials:

  1. The Colon (:): Every if line must end with a colon. It signals to Python: “The condition check ends here; the code block is about to begin.”
  2. Indentation (4 Spaces): As learned in syntax-and-comments, the lines that belong inside the if block must be indented by exactly 4 spaces. The first unindented line marks the end of the block.

2. The else Statement: Providing a Fallback

What if you want to take an alternative action when the condition is False? That is what else is for. It acts as your safety net:

user_age = 16

if user_age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not yet old enough to vote.")

Output:

You are not yet old enough to vote.

An else block never has a condition attached to it—it runs automatically whenever the preceding if condition evaluates to False.


3. The elif Ladder: Multi-Way Decisions

What if you have more than two mutually exclusive outcomes? For example, grading a test with letter grades $A, B, C, D,$ or $F$?

In Python, you chain multiple conditions together using elif (short for “else if”):

score = 83

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Final Grade: {grade}")

Output:

Final Grade: B

Crucial Rule: Order Matters!

Python evaluates an if / elif / else chain sequentially from top to bottom.

The instant it encounters the first condition that evaluates to True, it executes that branch and immediately skips all remaining branches—even if later conditions would also be mathematically true:

Look at this broken grading example:

# BROKEN LOGIC EXAMPLE:
score = 95

if score >= 60:
    print("Grade: D")  # Runs because 95 >= 60 is True!
elif score >= 90:
    print("Grade: A")  # NEVER RUNS, skipped completely!

Always structure your if / elif chains starting with the most specific or highest thresholds first.


4. Nested Conditions

You can place an if statement inside another if block. This is called nesting:

has_account = True
password_correct = True
is_two_factor_verified = False

if has_account:
    if password_correct:
        if is_two_factor_verified:
            print("Access granted to sensitive dashboard.")
        else:
            print("Prompting for 2FA verification code.")
    else:
        print("Invalid password.")
else:
    print("Account not found.")

Engineering Best Practice: Avoid Deep Nesting

While nesting works, deeply nested code (sometimes called the “Pyramid of Doom”) is hard to read and debug.

Whenever possible, flatten your logic using boolean operators (and, or) or early returns:

# Flat, clean, and professional:
if has_account and password_correct and is_two_factor_verified:
    print("Access granted to sensitive dashboard.")

5. Idiomatic Python: Testing Truthiness Directly

In type-casting, you learned that non-empty strings, non-zero numbers, and populated collections are inherently “truthy,” while empty values ("", 0, None, []) are “falsy.”

Because of this, you do not need to write redundant comparisons against True or lengths:

# NOISY & UNPYTHONIC:
if is_logged_in == True:
    print("Welcome")

if len(shopping_cart) > 0:
    print("Checkout")

# CLEAN & IDIOMATIC PYTHON:
if is_logged_in:
    print("Welcome")

if shopping_cart:
    print("Checkout")

If shopping_cart has items, it is truthy. If it is empty ([]), it is falsy and the block is skipped.


6. The Ternary Operator (Conditional Expressions)

Sometimes you want to assign a variable based on a simple condition. Rather than writing four lines of if / else boilerplate:

# Standard 4-line if-else:
age = 20
if age >= 21:
    drink_status = "Allowed"
else:
    drink_status = "Restricted"

Python provides an inline shortcut called a conditional expression (or ternary operator):

$$\text{value_if_true} \textbf{ if } \text{condition} \textbf{ else } \text{value_if_false}$$

# Clean single-line conditional expression:
age = 20
drink_status = "Allowed" if age >= 21 else "Restricted"

print(f"Status: {drink_status}")  # Status: Restricted

Use conditional expressions for simple, one-line assignments. If your logic requires multiple steps or side effects, use a standard if statement for readability.


7. Common Beginner Gotchas

MistakeWhy It BreaksHow to Fix
if x = 5:Single = is assignmentUse == for comparison: if x == 5:
if x > 10Missing colon at line endAdd colon: if x > 10:
Indentation mismatchUneven spaces in blockEnsure all lines in block use exactly 4 spaces
else if:Syntax from other languagesPython uses elif:

Summary Checklist

  • if condition:: Executes block only if condition evaluates to True.
  • else:: Catch-all fallback executed when preceding checks fail.
  • elif:: Chains multiple mutually exclusive checks; stops at first True.
  • Truthiness: Check non-empty values directly (if items:).
  • Ternary: Use a if condition else b for quick inline assignments.

Now that your programs can evaluate conditions, continue to match-case for Python’s modern structural pattern matching, or jump into loops to automate repetitive tasks.

Test your understanding of Conditions and Branching

Quick interactive practice questions with instant feedback.

Take Quiz →