17 min read Control Flow Lesson 7 of 16
Course 03 · Part 2 — Input, Operators & Control Flow

Decision Making & Conditions: How Programs Choose Paths

Moving Beyond Straight Lines: Branching Logic and Smart Execution Flow

In the previous lesson, we explored operators and expressions. We saw how the computer compares data to produce boolean truths—True or False. But if a program merely knows an answer and cannot act upon it, software remains completely static. If an account holder has sufficient balance, allow the withdrawal; otherwise, reject it with an overdraft notice. If a user is 18 or older, grant adult access; otherwise, route them to restricted settings. This fundamental capability to choose different paths based on runtime circumstances is called Conditional Decision Making.

The True Intelligence of Software: Branching

Up to this point, every script we wrote was a strict, one-way straight road—executing sequentially from line 1 through the final line without deviation. Real-world software, however, resembles a dynamic traffic interchange or maze. Depending on input data and evaluated conditions, execution branches left, right, or straight ahead. In Python, our core steering wheel for directing execution flow consists of `if`, `elif`, and `else` statements.

01 & 02 What is a Condition & The `if` Statement?

Stated concisely:

A Condition is an expression that evaluates to either True or False. The `if` statement is the instruction that commands: “Execute the indented code block below IF and ONLY IF this condition evaluates to True.”
age = 25
if age >= 18:
print("You are an adult.")

Because 25 >= 18 evaluates to True, Python steps inside the indented block following the colon and prints: You are an adult.

03 to 05 What Happens When a Condition is False? Indentation & Code Blocks

If the condition evaluates to False:

age = 15
if age >= 18:
# Since condition is False, the line below is completely skipped!
print("You are an adult.")
print("Program finished.") # Unindented: outside the if statement, always runs

In Python, Indentation is Syntax, Not Mere Styling!

Languages like C, Java, or JavaScript use curly braces { } to delimit blocks of code. Python discards curly braces entirely. Instead, lines indented with 4 spaces immediately after a colon (:) form a coherent Block. The indentation tells the Python interpreter exactly which statements belong to that specific conditional branch and when that branch concludes.

06 & 07 `else` — Handling the Alternative Path

In real software, when a condition fails, we rarely sit idle—we take a fallback action. In Python, the `else` clause provides the guaranteed alternative pathway:

age = 15
if age >= 18:
print("Access granted: Adult")
else:
print("Access denied: Minor")
age >= 18 ?
True ──> "Access granted: Adult"
False ──> "Access denied: Minor"

08 to 10 `elif` — Multi-Way Branching & Condition Evaluation Order

Real-world scenarios often have multiple outcomes rather than a simple binary yes/no. Examination grading, traffic light signals, tax brackets, and membership tiers have numerous distinct categories. Python contracts else if into `elif`:

grading.py
score = 75
if score >= 80:
print("Grade: A (Excellent)")
elif score >= 70:
print("Grade: B (Good)")
elif score >= 60:
print("Grade: C (Pass)")
else:
print("Grade: F (Fail)")

Why Evaluation Order Matters Critically

Python evaluates conditions sequentially from top to bottom. The moment it encounters the first condition that evaluates to True, it executes that branch's block and immediately exits the entire if/elif/else ladder! If you accidentally wrote if score >= 60: first and elif score >= 80: later, a student scoring 95 would trigger the 60 threshold first and falsely receive “Grade C”! Always structure multi-tier checks from the most restrictive or highest threshold down to the lowest.

11 to 14 Combining Conditions with Logical Operators (`and`, `or`, `not`)

By embedding the logical operators and, or, and not inside conditional statements, we can enforce complex business logic in clean, readable syntax:

1. and (all conditions must be True):
if age >= 18 and has_id:
print("Voting permitted.")
2. or (at least one must be True):
if is_admin or is_owner:
print("Dashboard unlocked.")
3. not (inverts truth value):
if not is_suspended:
print("Account in good standing.")

15 to 17 Text Comparison & A Practical Login Gate

Conditions apply equally to textual string data. Strings are compared using the exact same equality operators:

login_gate.py
user = input("Username: ")
password = input("Password: ")
# Testing string equality for authentication
if user == "salim" and password == "secret123":
print("Login successful! Welcome to the console.")
else:
print("Access denied: Invalid credentials.")

18 & 19 Nested Conditions vs. Pythonic Chained Comparisons

Placing an if statement inside another if block creates a Nested Condition. While sometimes necessary, excessive nesting hurts readability. Python provides mathematical chained comparisons for checking bounded ranges cleanly:

Traditional verbose syntax:
if score >= 40 and score <= 100:
print("Valid range")
Pythonic chained syntax (clean & readable):
if 40 <= score <= 100:
print("Valid range")

20 to 22 Truthy and Falsy Values

In Python, any object or data type can be evaluated in a conditional context as though it were a boolean:

Falsy Values (evaluate to False):
  • • Explicit booleans: False, and None
  • • Numeric zeros: 0, 0.0
  • • Empty strings: ""
  • • Empty collections: [], {}
Truthy Values (evaluate to True):
  • • Any non-zero numeric value (e.g., 1, -5, 3.14)
  • • Any non-empty string (e.g., "Salim", " ")
  • • Any collection or object containing items
# Idiomatic Python check for presence of input:
user_input = "Salim"
if user_input:
print("Input provided!") # Executes because string is non-empty (truthy)

23 to 25 Branching Architecture & The Road to Loops

Our mental model of computation is now nearly complete:

Problem → Input → Variables & Types → Operators → Conditions → Branching Decisions

Our code can now make intelligent decisions. But imagine if this decision-making logic had to run for 1,000 students or 100,000 bank accounts. Would we copy and paste the code 1,000 times? Never! The true superhuman strength of a computer is tireless, instantaneous repetition. That brings us to our next great milestone: Loops (Iteration)!

26 Hands-on Practice Challenges

Open conditions_practice.py in your code editor and solve the following 6 practical challenges:

Challenge 1: Adult or Minor Verification Prompt for an age integer and print either "Adult" or "Minor" using an if/else statement.
Challenge 2: Positive, Negative, or Zero Take a number as input and determine whether it is Positive, Negative, or Zero using if/elif/else.
Challenge 3: Even or Odd Determination Use the modulo operator (number % 2 == 0) to evaluate whether an integer is "Even" or "Odd".
Challenge 4: Examination Grading Scale Prompt for a numeric exam score and classify it hierarchically: 80+ (A), 70+ (B), 60+ (C), 40+ (D), and below 40 (F).
Challenge 5: Secure Credential Validation Prompt for username and password. Use an and operator to check against preset credentials and grant or deny access.
Challenge 6: Shopping Discount Threshold If the customer's total purchase amount is $5,000 or greater, apply a 20% discount; otherwise, display the full subtotal with zero discount.

27 🧠 Key Takeaways & Summary

The `if` Statement: Executes a target block of instructions only when its condition evaluates to True.
The `else` Clause: Provides a guaranteed fallback execution path when the primary condition fails.
The `elif` Chain: Tests multiple sequential alternatives in order, terminating the ladder upon the very first true match.
Indentation & Blocks: 4 spaces after a colon define lexical scope and structural boundaries in Python.
Branching: Transforms linear scripts into intelligent, adaptive systems capable of choosing distinct behaviors dynamically.

Next Lesson: Loops — Repeating Tasks

How do we execute instructions hundreds or millions of times effortlessly? Discover the automated magic of for and while loops.