Skip to contentSkip to navigation
Module 02 • Lesson 04Control Flow & BranchingGuard Clauses & Pattern Matching

Conditional Branching (if / elif / else)

Every dynamic software system—from credit card fraud detection engines at Stripe evaluating million-dollar transactions to spacecraft flight control computers at NASA aborting launch sequences—operates on conditional branching. Without branching, code can only execute linear sequences of static instructions. Mastering if...elif...else, chained inequalities, short-circuit guard clauses, and pattern matching allows engineers to build resilient software that gracefully handles edge cases, prevents null dereferencing crashes, and models complex business logic cleanly. Crucial for Backend Engineers, Security Analysts, and Systems Architects.

Estimated Time
15 min read
Difficulty Level
Beginner Friendly
Knowledge Check
15 Questions
Interactive Code Runner Active
01 / Foundations

The Mechanics of Conditional Branching & Virtual Machine Jumps

In pure sequential execution, a CPU advances its instruction pointer linearly down a program text. Dynamic intelligence requires deviation: validating credentials before opening database connections, rejecting anomalous transactions before credit cards charge, or decelerating autonomous vehicles when radar spots obstacles.

Python expresses decision branching through if...elif...else constructs and modern structural pattern matching (match...case, PEP 634). Rather than using curly braces, Python implements the off-side rule, utilizing significant 4-space indentation to define lexical scope.

1. Bytecode Jump OpcodesPVM Core

CPython evaluates branch conditions using POP_JUMP_IF_FALSE. When a branch succeeds, an unconditional JUMP_FORWARD instruction guarantees that remaining elif or else blocks are completely bypassed.

2. Chained Comparison OptimizationSyntax

Expressions like 10 <= x <= 50 compile cleanly into (10 <= x) and (x <= 50). Crucially, the middle operand x is evaluated exactly once, preventing redundant computation.

3. Guard Clause FlatteningArchitecture

Inverting conditions into early-return guard clauses eliminates the deeply nested "Arrow Anti-Pattern" (Pyramid of Doom), keeping the primary happy path flat at zero indentation.

Think of it like this: The Railway Switch Track & Inspection Siding

Think of conditional branching like a railway switch yard. A locomotive speeds along the main line. At each switch (if / elif), a track sensor reads the signal. If the signal is green (True), the switch throws, sending the train into that specific route. Immediately after the train enters, the line merges past all remaining switches via an express bypass track (JUMP_FORWARD), preventing the train from ever hitting the other sidings. Guard clauses act like early safety derailers at the yard entrance—ejecting bad train cars immediately before they can enter and stall the primary rail yard!

Side-by-Side Contrast: C / Java / JS vs Python Branching Design
Syntax & Scope Philosophy
C / Java Curly Braces & Assignment Traps

In C, writing if (x = 5) accidentally assigns 5 to x and evaluates truthy, creating notorious bugs. Furthermore, single-line unbraced if statements suffer from the "dangling else" ambiguity (as seen in Apple's famous iOS goto fail; SSL bug).

// C/Java: Accidental assignment danger if (role = "admin") { // Bugs silently in C! grantAccess(); }
Python Significant Indentation & Syntax Guarantees

Python's parser explicitly forbids assignment = inside if conditions, converting typos into compile-time SyntaxErrors. Indentation is mandatory, completely eliminating dangling else bugs and missing-brace vulnerabilities.

# Python: Safe syntax and chained inequalities if 18 <= age <= 65 and is_verified: grant_access() # if role = "admin": -> SyntaxError at compile time!
Python
# Try Python's chained comparisons and guard clauses
def assess_credit(score: int, is_flagged: bool) -> str:
    # Guard clause: early exit on fraud flags
    if is_flagged:
        return "DECLINED: Security Flag"
        
    # Chained comparison and inline ternary
    if 750 <= score <= 850:
        return "TIER_1: Prime Preferred"
    elif 650 <= score < 750:
        return "TIER_2: Standard Approval"
    return "TIER_3: Subprime / Review"

print("Score 800:", assess_credit(800, False))
print("Score 700:", assess_credit(700, False))
print("Score 800 Flagged:", assess_credit(800, True))
POP_JUMP_IF_FALSE

Virtual machine opcode popping TOS truthiness and diverting instruction pointers to alternative branches on zero.

The Off-Side Rule

Syntactic rule where lexical indentation depth establishes block boundaries via INDENT and DEDENT tokens.

Chained Inequalities

a < b < c compiles into (a < b) and (b < c) with single evaluation of intermediate sub-expressions.

match...case (PEP 634)

Structural pattern matching with destructuring, pattern guards, and case _ wildcards introduced in Python 3.10.

02 / Syntax Anatomy

Dissecting a Production Credit Authorization Statement

Click each constituent token of this credit risk decision statement to inspect assignment scopes, relational comparisons, and bytecode branch jumps.

Token 1 of 5

status =• Assignment Target & Scope Binding

Control Flow Component
Syntactic Role

Variable binding target receiving the final evaluated branch outcome.

CPython Under the Hood

Emits STORE_FAST in functions or STORE_NAME in module scope, referencing the object pointer produced by whichever branch evaluated.

Evaluation Invariant
In Python, variables defined or assigned inside if-else blocks share the enclosing function or module scope. Unlike C or Java, if blocks do not create block scope.
Common Production Trap

Accidentally using assignment '=' inside conditional expressions instead of equality '=='. Writing 'if x = 5:' produces an immediate SyntaxError at parse time.

if...elif...else
Mutually exclusive ladders
Chained Inequalities
a <= b <= c single eval
Ternary x if C else y
Inline value selection
Early Guard Clauses
Flatten nested pyramids
match...case
PEP 634 pattern dispatch
03 / Branch Pipeline

The CPython Bytecode Jump & Evaluation Lifecycle

Follow how the Python Virtual Machine evaluates boolean truthiness, executes conditional jumps, and skips dormant blocks.

01

Condition Stack Push & Truthiness Probe

CPython Virtual Machine (Python/ceval.c)

The evaluation loop executes the condition expression, pushing the resulting PyObject* onto the operand evaluation stack.

CPython checks truthiness using PyObject_IsTrue(). If the object defines __bool__(), it calls it; otherwise it checks __len__() != 0.

Internal Representation / Bytecode Emitted
LOAD_FAST score
LOAD_CONST 750
COMPARE_OP (>=
PyObject_IsTrue(TOS)
04 / Branching Matrix

Architectural Trade-offs: Branching Patterns & Clean Code

Compare flat guard clauses against nested pyramids, mutally exclusive ladders against independent if blocks, and pattern matching against ladder chains.

Idiomatic Clean Pattern
if not valid: return None (Early exit keeps happy path flat)
Fragile or Anti-Pattern Variant
if valid:
    if active:
        if authorized:
            return True
Subtle Production Hazard

The 'Pyramid of Doom' causes code to drift rightwards across the editor, making error handling and testing painful.

Engineering Best Practice

Adopt guard clauses: check validation and error conditions early and return immediately, keeping main logic at zero indentation.

CPython: Early returns emit immediate RETURN_VALUE instructions, discarding local frame allocations without traversing redundant jump trees.
05 / Syntax Sandbox

Complete Conditional Branching Syntax Sandbox

Execute these 15 real-world branching patterns in your browser, covering chained comparisons, truthiness checks, guard clauses, and match...case statements.

Python
# 1. Basic if statement
temperature = 32
if temperature > 30:
    print("High temperature warning")

# 2. Two-way branching: if...else
age = 16
if age >= 18:
    print("Eligible to vote")
else:
    print("Under voting age")

# 3. Multi-way branching: if...elif...else
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

# 4. Chained comparisons (mathematical inequality)
value = 25
if 10 <= value <= 50:
    print("Value lies within operational range [10, 50]")

# 5. Idiomatic truthiness check on collections
cart_items = []
if not cart_items:
    print("Cart is currently empty")       # Empty list evaluates to False

# 6. Idiomatic truthiness check on strings and None
username = "alex"
if username:
    print(f"Logged in as {username}")     # Non-empty string evaluates to True

# 7. Ternary conditional expression (inline if-else)
status = "Adult" if age >= 18 else "Minor"

# 8. Combining conditions with 'and', 'or', 'not'
role = "manager"
has_mfa = True
if (role == "admin" or role == "manager") and has_mfa:
    print("Elevated privileged access granted")

# 9. Membership testing in conditional
allowed_roles = {"admin", "auditor", "operator"}
if role in allowed_roles:
    print("Role authorized")

# 10. Identity checking with None
result = None
if result is None:
    print("No computation result found")

# 11. Early return guard clause pattern
def safe_divide(numerator: float, denominator: float) -> float | None:
    if denominator == 0:
        return None                       # Early exit guards against ZeroDivisionError
    return numerator / denominator

# 12. Nested conditionals
account_balance = 500
withdrawal_amount = 100
is_account_active = True
if is_account_active:
    if withdrawal_amount <= account_balance:
        account_balance -= withdrawal_amount
        print("Withdrawal successful")
    else:
        print("Insufficient funds")

# 13. Structural pattern matching (Python 3.10+ match...case)
http_code = 404
match http_code:
    case 200:
        print("OK")
    case 401 | 403:
        print("Access Denied")
    case 404:
        print("Resource Not Found")
    case 500:
        print("Internal Server Error")
    case _:
        print(f"Unhandled Status Code: {http_code}")

# 14. Pattern matching with condition guard
sensor_reading = 120
match sensor_reading:
    case val if val > 100:
        print("Critical threshold exceeded!")
    case _:
        print("Normal sensor reading")

# 15. The 'pass' statement as a no-op placeholder
if age < 0:
    pass                                  # Placeholder for future error handler
06 / Hands-on Walkthroughs

Progressive Code Walkthroughs: From Academic Honors to API Gateways

Follow 3 industry architectures illustrating academic grading boundaries, e-commerce discount matrices, and edge API security gateway filters.

Problem Scenario & Constraints

Construct a university grading and Latin honors distinction classifier. The program accepts an exam score (0.0 to 100.0), validates that the score is within mathematical boundaries, assigns a letter grade (A+, A, B, C, F), and determines honors distinctions (Summa Cum Laude for scores >= 98.0, Magna Cum Laude for >= 95.0, Cum Laude for >= 90.0, Dean's List for >= 80.0, Satisfactory for >= 70.0, Passing for >= 60.0, and Academic Probation for failing scores).

Production Implementation
07 / Common Anti-Patterns

Six Critical Conditional Branching Anti-Patterns

Avoid assignment vs comparison bugs, redundant boolean checks, deeply nested arrow pyramids, and unidiomatic collection emptiness traps.

🟢 Beginner Pitfall: Accidental Assignment vs Comparison Syntax Error
Buggy Code (What Fails)
user_role = "guest"
if user_role = "admin":
    grant_superuser_access()

Error Behavior: SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Clean Fix (Production Standard)
if user_role == "admin":
    grant_superuser_access()

Architectural Invariant: In Python, a single = is the variable assignment operator, not a comparison operator. Python's parser strictly forbids = inside if conditions to prevent the subtle assignment bugs common in C and C++.

08 / Real-World Systems

How Industry Giants Structure Critical Decision Logic

From Stripe fraud classification to Kubernetes horizontal pod autoscalers, LiDAR obstacle collision avoidance, and hospital emergency triage.

FinTech & Payment ProcessingProduction Tested

🟢 Simple Script: Stripe-Style Transaction Fraud Risk Classifier

Real-time payment processors evaluate transactional risk scores to approve, challenge with 3D Secure (MFA), or outright decline credit card transactions.

Python
risk_score = 78  # Risk assessment score between 0 and 100
is_cvc_matched = True
is_billing_country_mismatch = True

if risk_score >= 85:
    action = "DECLINE: High Risk Assessment"
elif risk_score >= 65:
    if not is_cvc_matched or is_billing_country_mismatch:
        action = "MANUAL_REVIEW: Step-up 3D Secure Required"
    else:
        action = "APPROVE: Elevated Risk with Strong CVC"
else:
    action = "APPROVE: Low Risk Transaction"

print(f"Risk Score: {risk_score} -> Decision: {action}")
Why it matters: Payment gateways combine numeric score thresholds with boolean cardholder verification flags. Nesting the CVC check within the intermediate risk band (65-84) allows low-friction approvals for trusted transactions while triggering step-up authentication for suspicious mismatches.
Cloud Infrastructure & SREProduction Tested

🟡 Scaled Service: Elastic Kubernetes Pod Horizontal Auto-Scaler Decider

Container orchestration platforms evaluate telemetry metrics across server clusters to scale replica counts up or down.

Python
avg_cpu_percent = 84.5
avg_memory_percent = 62.0
current_replicas = 8
max_replicas = 20
min_replicas = 2

if avg_cpu_percent > 80.0 or avg_memory_percent > 75.0:
    if current_replicas < max_replicas:
        desired_replicas = current_replicas + 2
        decision = f"SCALE_UP: Added 2 replicas (Target: {desired_replicas})"
    else:
        decision = "SCALE_ALERT: Cluster at maximum replica capacity!"
elif avg_cpu_percent < 30.0 and avg_memory_percent < 40.0:
    if current_replicas > min_replicas:
        desired_replicas = current_replicas - 1
        decision = f"SCALE_DOWN: Removed 1 replica (Target: {desired_replicas})"
    else:
        decision = "SUSTAIN: Cluster already at minimum replica capacity"
else:
    decision = "SUSTAIN: Workload operating within nominal thresholds"

print(f"Auto-scaler Decision: {decision}")
Why it matters: Cloud auto-scalers must avoid rapid oscillation ('thrashing'). Multi-way branching with hysteresis thresholds (>80% for scale-up vs <30% for scale-down) ensures stability under varying cloud traffic loads.
Autonomous Systems & RoboticsProduction Tested

🔴 Enterprise Production: LiDAR Obstacle Collision Avoidance Decision Matrix

Self-driving vehicles and autonomous mobile robots (AMRs) process laser distance telemetry to trigger emergency maneuvers.

Python
obstacle_distance_meters = 2.4
vehicle_speed_kmh = 45.0
is_pedestrian_detected = True

if obstacle_distance_meters < 3.0 or (obstacle_distance_meters < 6.0 and is_pedestrian_detected):
    emergency_action = "EMERGENCY_BRAKE_ACTUATED"
elif obstacle_distance_meters < 10.0 and vehicle_speed_kmh > 30.0:
    emergency_action = "REDUCE_THROTTLE_AND_STEER"
elif obstacle_distance_meters < 20.0:
    emergency_action = "WARN_OPERATOR"
else:
    emergency_action = "MAINTAIN_CRUISE_VELOCITY"

print(f"Distance: {obstacle_distance_meters}m | Action: {emergency_action}")
Why it matters: Robotics control loops evaluate sensory ranges where safety margins expand dynamically when vulnerable road users (pedestrians) are identified.
Healthcare & Hospital LogisticsProduction Tested

🔴 Enterprise Production: Emergency Department Triage Acuity Index (ESI) Classifier

Hospital electronic health record (EHR) systems classify incoming patients into Emergency Severity Index (ESI) triage categories 1 through 5.

Python
is_unresponsive = False
is_high_risk_confusion = False
severe_pain_scale = 8  # 1 to 10
resource_needs_count = 2

if is_unresponsive:
    esi_level = 1  # Immediate life-saving intervention
elif is_high_risk_confusion or severe_pain_scale >= 9:
    esi_level = 2  # Emergent: High risk situation
elif resource_needs_count >= 2:
    esi_level = 3  # Urgent: Multiple diagnostic resources needed
elif resource_needs_count == 1:
    esi_level = 4  # Less Urgent: One resource (e.g. X-ray)
else:
    esi_level = 5  # Non-urgent

print(f"Patient Triage Assigned: ESI Level {esi_level}")
Why it matters: Clinical decision support systems rely on hierarchical triage classification where life threats supersede all lower-level diagnostic resource counts.
09 / Stripe Radar Case Study
Fraud Detection ArchitectureProduction Architecture

Stripe: Fraud Screening Rule Evaluation Engine

Scale
Screening billions of credit card transactions annually across hundreds of thousands of merchants worldwide.

Stripe Radar is an advanced machine learning and rule-based fraud detection engine built directly into Stripe's payment gateway. In addition to global AI models, Stripe allows merchants to define custom business rules, such as: 'Block if risk_score > 75 and :card_country: != :ip_country:' or 'Request 3D Secure if amount_in_usd > 1000 and not :is_authorized_device:'.

Because payment authorizations must complete within 100 milliseconds, Stripe compiles merchant rules into optimized conditional trees. Lightweight, fast-evaluating checks (like comparing two country codes or checking an IP blacklist set) are positioned first as short-circuit guard clauses. If a transaction fails an initial security constraint, the gateway rejects it immediately without incurring the computational expense of deep behavioral feature calculations.

Radar Short-Circuit Guard Clause Rule Pattern
Python
# Simulated Stripe Radar custom merchant rule evaluation engine
def evaluate_radar_rules(txn: dict) -> str:
    # Guard 1: High fraud risk threshold
    if txn.get("risk_score", 0) > 85:
        return "BLOCK: Automated Radar ML High Risk"
    
    # Guard 2: Country mismatch on high-value transaction
    card_country = txn.get("card_country")
    ip_country = txn.get("ip_country")
    amount = txn.get("amount_usd", 0.0)
    
    if amount > 500.0 and card_country != ip_country:
        return "CHALLENGE: 3D Secure Authentication Required"
        
    # Guard 3: Card verification failure
    if txn.get("cvc_check") != "pass":
        return "BLOCK: CVC Check Failed"
        
    return "ALLOW: Transaction Cleared"

transaction = {
    "amount_usd": 750.0,
    "card_country": "US",
    "ip_country": "FR",
    "risk_score": 42,
    "cvc_check": "pass"
}
print("Radar Decision:", evaluate_radar_rules(transaction))
Key Engineering Principles
Rule 01

Structure multi-stage verification pipelines using sequential guard clauses to reject invalid inputs as early as possible.

Rule 02

Combine numerical thresholds (amount > 500.0) with equality checks (card_country != ip_country) to pinpoint fraud vectors.

Rule 03

Short-circuit early exits drastically reduce average latency and cloud compute expenditure in high-throughput APIs.

10 / Guided Labs

Guided Branching Labs & Interactive Debugging

Classify number sign and parity, build mortgage pre-approval risk tier evaluators, and construct pattern-matched HTTP status code routers.

Code Completion+5 XP

Number Parity and Sign Classifier

Instructions:

If number is 0, print 'Zero'. Otherwise, determine whether it is 'Positive' or 'Negative', and whether it is 'Even' or 'Odd' (using % 2). Print the combined string.

Interactive Workspace
Python
# Classify integer 'number' into sign and parity
# Expected output for number = 7: 'Positive Odd'
# Expected output for number = -4: 'Negative Even'
# Expected output for number = 0: 'Zero'

number = 7
# Write conditional logic below:
Hints & Clues
  • Check for 0 first: if number == 0: print('Zero')
  • Use a ternary or if-else: 'Positive' if number > 0 else 'Negative'
  • Check even/odd with number % 2 == 0
11 / Open-Ended Practice Tasks

Independent Engineering Challenges

Construct warehouse logistics rating calculators and employee overtime payroll engines without starter scaffolding.

Develop an automated logistics package rating calculator. Given a package's weight in kilograms and destination zone ('Local', 'Regional', 'National', 'International'), compute base shipping, apply overweight surcharges for parcels exceeding 10 kg ($2.50 per kg over 10 kg), and add an optional fuel surcharge for national and international zones.

Requirements Checklist:
  • Variables: weight_kg = 14.0, zone = 'National', has_fuel_surcharge = True.
  • Base rates: 'Local' -> $5.00, 'Regional' -> $10.00, 'National' -> $18.00, 'International' -> $45.00.
  • If weight_kg > 10.0, compute overweight_fee = (weight_kg - 10.0) * 2.50.
  • If has_fuel_surcharge is True and zone in ('National', 'International'), add $4.50.
  • Calculate total and print: 'Zone: National | Weight: 14.0 kg | Surcharges: $14.50 | Total: $32.50'.
Starter Scaffolding
Python
weight_kg = 14.0
zone = "National"
has_fuel_surcharge = True
# Calculate shipping rating
12 / Key Takeaways & Glossary

Conditional Branching Reference Summary

Review foundational guidelines for structuring clean decision trees, implementing early exits, and avoiding branching traps.

Guard Clauses

Early-exit statements handling boundary checks and invalid parameters at the top of functions, keeping primary logic flat.

Chained Checks

min <= x <= max evaluates the middle expression exactly once, offering expressive mathematical interval verification.

Ternary Assignments

a if condition else b evaluates lazily, concisely selecting values without verbose multi-line statement blocks.

Pattern Matching

match...case constructs (PEP 634) provide declarative value, sequence, and mapping dispatch with wildcard case _ fallbacks.

Core Engineering Invariants
1Use if...elif...else ladders to evaluate multi-condition decisions; Python executes the first truthy branch and skips all remaining branches.
2Chained comparisons (e.g. 10 <= x <= 50) provide clean mathematical interval validation and evaluate the middle operand only once.
3Leverage Python's built-in truthiness: empty containers ([], {}, set()), numerical zeros (0, 0.0), '', and None are falsy; write 'if not items:' instead of 'if len(items) == 0:'.
4Use ternary conditional expressions ('a if condition else b') for concise inline variable assignments.
5Adopt the Guard Clause (Early Exit) pattern to avoid the deeply nested 'Arrow Anti-Pattern' and keep the happy path flat.
6Never compare booleans with '== True' or '== False'; evaluate booleans directly ('if is_valid:').
7Structural pattern matching (match...case) offers clean, declarative multi-value matching with wildcard ('case _:') fallbacks.
Decision Control Flow Constructs SummaryCPython Standards
ConstructPrimary PurposeBytecode MechanismBest Practice Guideline
if statementSingle conditional execution gatePOP_JUMP_IF_FALSEUse for early guard clauses and validation checks.
if...elif...elseMutually exclusive multi-range branchingJUMP_FORWARD on matchEvaluate continuous numeric intervals in descending order.
x if cond else yTernary value selection expressionLazy branch jumpKeep clean on a single line; avoid nested ternaries.
match...caseStructural pattern matching & enum routingMATCH_MAPPING / SEQUENCEUse for discrete literals and protocol token matching.
13 / Knowledge Assessment Quiz Booster
Score: 0 / 7

Test Your Mastery: Conditional Decision Structures

Answer these 7 concept questions. Immediate feedback and architectural explanations are provided on selection.

Question 1 of 7medium

What is the value of result after evaluating this ternary expression?<pre>val = 15 result = "High" if val > 20 else ("Medium" if val > 10 else "Low")</pre>

14 / Study Guide & FAQ
Growth Mindset: Embrace Flat, Simple Logic

The hallmark of a senior software engineer is not complex, deeply nested logic—it is the discipline to write flat, transparent code that reads like clear English prose. By applying early-return guard clauses and concise chained comparisons, you make your software easy to debug, easy to test, and effortless to maintain.

Frequently Asked Questions

Architectural insights into if-elif ladders, boolean equality pitfalls, guard clauses, and pattern matching.

Q1.What is the difference between multiple 'if' statements and an 'if...elif' ladder?

Multiple independent 'if' statements evaluate every single condition sequentially, meaning multiple blocks can execute if multiple conditions are True. In an 'if...elif...else' ladder, Python evaluates conditions from top to bottom and stops as soon as the first True branch is found, guaranteeing that at most one branch runs.

Q2.Why should I avoid writing 'if x == True:'?

Comparing against '== True' is unidiomatic and dangerous. First, 'if x:' already checks if x evaluates to True. Second, '== True' checks strict equality with the boolean True, which fails on other truthy values (such as non-empty lists or strings like 'admin'), breaking Python's truth value protocol.

Q3.What is the 'Arrow Anti-Pattern' and how do guard clauses fix it?

The Arrow Anti-Pattern (or Pyramid of Doom) occurs when nested 'if' statements cause code to indent deeper and deeper (resembling an arrowhead '>'). Guard clauses fix this by checking for error or exit conditions at the top of the function and returning immediately ('if not valid: return None'), keeping the primary logic unnested at the baseline indentation level.

Q4.When should I use 'match...case' instead of 'if...elif...else'?

Use 'match...case' when comparing a variable against specific discrete literal values, enums, command strings, HTTP status codes, or when destructuring sequences and dictionaries. Use 'if...elif...else' when testing complex boolean logic or continuous numeric ranges (e.g. score >= 80).

Ready to Build Resilient Branching Logic?

Solve number sign and parity challenges, build mortgage loan pre-approval engines, and take the lesson quiz to verify your conditional branching mastery.

Flat Guard Clauses

Eliminate deeply nested arrow pyramids and structure clean early exits.

+40 XP Reward

Earn experience points toward your developer rank as soon as you pass.

~3 Minutes to Complete

Bite-sized knowledge check with instant explanations for every question.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Conditional Branching (if / elif / else) practice

Sign-in required

Set number to 7. Use an if/else statement to print odd when the number has a remainder of 1 after division by 2; otherwise print even.

Expected output:

odd

Coding Practice is Locked

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.

Practice quiz

Check yourself

15 questions with explanations after submission, so you can correct course as you go.

Conditional Branching (if / elif / else) quiz

Locked

You must be signed in to take this quiz. Sign in to test your understanding, track your answers, and earn XP.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/6 complete
Module cheat sheet