If Elif and Else Statement

Acadestine

Learning Objectives
    • Control program flow dynamically using the if keyword.
    • Chain multiple conditional evaluations using elif and establish fallback paths with else.
    • Apply Python indentation rules correctly to define execution blocks inside conditional branches.

Choose Your Own Adventure in Code

Up until now, your Python scripts have likely executed like a simple recipe running line by line from top to bottom without skipping a beat. To build modern, intelligent applications, your code must be able to make decisions and adapt to different situations.

This shift in how code runs is the difference between a rigid script and dynamic software.

  • Sequential Execution: Python executes every line of code in strict order, from first to last, regardless of context.
  • Conditional Execution: Python evaluates a real-time condition first, then decides which path of code to run (and which lines to skip entirely).

Think of conditional execution like a "Choose Your Own Adventure" book or your own morning routine. You do not blindly put on a heavy winter coat every single day; you check the temperature outside first and branch your decision based on what you find.

Execution Type Code Behavior Real-World Metaphor
Sequential Runs every single line, every single time. Reading a standard novel from page 1 straight to the end.
Conditional Chooses a specific path based on current data. Checking if a traffic light is green before pressing the gas pedal.

Here is a quick look at how decision branching works in Python syntax:

weather = "raining"

if weather == "raining":
    print("Grab an umbrella!")

Output:

Grab an umbrella!

When you run this script, Python checks the value stored in the weather variable. Because the condition is met, Python executes the nested print() statement. By introducing decision branching, you give your programs the power to react dynamically to changing data.

Unlocking Dynamic Software

Without decision-making, a computer program is just a rigid script that executes the exact same lines in the exact same order every single time. By introducing dynamic responsiveness, you empower your code to react intelligently to changing data and user inputs.

Why Responsiveness Matters

Think about the applications you interact with every day. They aren't static lists of instructions; they adapt to your choices in real time.

Here are a few ways dynamic responsiveness transforms fixed scripts into modern software: * Personalized User Experiences: Displaying a custom dashboard for a logged-in user versus a generic sign-up page for a guest. * Adaptive Security: Granting administrative permissions only when an identity check evaluates to True. * Smart UI Adjustments: Toggling an mobile application interface to dark mode automatically based on the user's system preferences.

When you write code that evaluates dynamic conditions, your software stops being a linear track and starts behaving like an intelligent, interactive system.

Looking Ahead: Layering Decisions

So far, you have seen how a single conditional evaluation can alter execution flow. But real-world software often requires checking decisions inside other decisions.

Imagine you are building a video streaming service. First, your app checks if a user is currently logged in. If they are, it might then perform a second check: Does this user have a high-definition tier subscription?

This concept is known as nested conditionals placing one conditional decision block inside another. As you build more complex applications, you will learn how to structure these layered choices to build rich, branching logic in your Python programs.

The Traffic Controller Metaphor

Imagine driving up to a busy intersection. The traffic signal above you turns bright red, and in an instant, you know exactly which action to take: you bring your car to a complete stop.

Software works using this exact same real-world logic. Instead of running every line of code indiscriminately, your program acts as a traffic controller that checks a signal first and then directs execution down a specific route.

Evaluated Conditions as Traffic Signals

In programming, a condition acts as your traffic signal. When your code arrives at a decision point, it pauses to check the current state of a signal before deciding where to go next.

When your code checks a condition, it follows a simple process:

  • Signal Check: The program evaluates a condition to determine its current state (such as True or False).
  • Decision Branching: The program checks which route matches that specific signal outcome.
  • Path Selection: Execution travels down the matching path while skipping all other options.

Just like a green light signals "go" and a red light signals "stop," an evaluated condition tells your program precisely which branch of code is cleared for execution.

Mutually Exclusive Paths

When you are at an intersection, you cannot drive straight ahead into the crossroad and hit your brakes to stay stationary at the exact same moment. The actions are mutually exclusive, meaning choosing one path automatically rules out the others.

Your program handles decision-making the same way. When presented with multiple choices based on a signal, only one path executes per check. Once your program picks a route, it drives completely down that path and skips the alternative roads entirely.

Traffic Signal Analogy Technical Software Concept
Checking the color of the light Evaluating a condition
Light status (e.g., Green vs. Red) State outcome (e.g., True vs. False)
Driving down only one chosen lane Executing a mutually exclusive path
Ignoring the red light actions when the light is green Skipping unselected execution paths

By thinking of your program as a system of signals and lanes, you can easily map out complex decision pathways without getting lost in the execution flow.

The Big Three: If, Elif, and Else

Now that you have the mental model of a traffic controller, it is time to write the actual code that directs your program's path. In Python, we control execution flow using three fundamental keywords: if, elif, and else.

Copy the code below into your environment and run it to see how Python evaluates each branch in sequence:

Console

        

Output:

It's a pleasant day! A t-shirt is fine.

Breaking Down the Mechanics

Let's dissect how this conditional structure works line-by-line so you can write your own error-free logic.

  • The if Keyword: This starts your decision tree. Python checks the condition temperature > 25. Because 18 > 25 evaluates to False, Python skips the indented block directly underneath it and moves to the next evaluation.
  • The elif Keyword: Short for "else if", elif allows you to chain additional conditions. Python checks temperature > 15. Since 18 > 15 evaluates to True, Python executes the code inside this block and completely skips the rest of the conditional structure.
  • The else Keyword: This acts as your safety net or fallback path. It doesn't take a condition it simply executes if every preceding if and elif condition evaluates to False.

A very common beginner mistake is forgetting the mandatory colon (:) at the end of an if, elif, or else line. That tiny character tells Python that a code block is about to begin!

The Golden Rule of Indentation

Unlike many other programming languages that use curly braces {} to group code, Python relies entirely on whitespace to define execution blocks.

Notice how the print() statements are shifted to the right beneath each keyword. The standard Python convention is to use 4 spaces for every level of indentation.

Here is how Python interprets your indentation structure:

Element Syntax Rule Purpose
Header Line Keyword + Condition + Colon : Sets up the logical check (e.g., if temperature > 25:).
Indented Block Exactly 4 spaces inward Contains the code that runs only if that specific check passes.
Unindented Code Back to the baseline margin Signals that the conditional block has ended and normal execution resumes.

If you mix up your spacing or forget to indent after a colon, Python will throw an IndentationError and stop your program immediately. Keep your indentation neat, and your code will execute smoothly every time!

The First-True-Wins Inspection

Imagine a bouncer at an exclusive event checking guests against a priority list from top to bottom. The moment you match a rule on that list, you are handed your VIP pass, and the bouncer completely stops reading the rest of the rules. Python evaluates conditional chains using this exact "first-true-wins" rule, executing only the first branch that evaluates to True and ignoring everything else below it.

Run this code in your environment to see how Python evaluates overlapping conditions:

Console

        
# Output:
Senior Discount Applied!
Enjoy the show!

Let's do a step-by-step breakdown of how Python inspected your code under the hood:

  • age = 68: You create a variable named age and store the integer 68 in memory.
  • if age >= 65:: Python begins its sequential condition check at the very top. It evaluates 68 >= 65, which is True.
  • print("Senior Discount Applied!"): Because the first condition evaluated to True, Python applies the first-match execution rule. It enters this block and prints "Senior Discount Applied!".
  • elif age >= 18: and subsequent branches: Python completely ignores these branches! Even though 68 >= 18 is mathematically True, Python bypasses all unfulfilled and remaining branches the moment it finds its first win.
  • print("Enjoy the show!"): Once the active branch finishes, execution jumps all the way past the entire if-elif-else structure to run the next unindented line of code.
Condition Check Sequence Evaluation Action Taken
if age >= 65 True Executes block and exits the entire conditional structure immediately.
elif age >= 18 Skipped Never evaluated because a previous branch already succeeded.
elif age >= 65 Skipped Never evaluated, demonstrating why branch order matters.
else Skipped Fallback path is ignored entirely.

Because Python works sequentially from top to bottom, the order in which you write your conditions determines which code actually gets to run. Always put your most specific conditions at the top of your if-elif chains so lower branches don't accidentally intercept them!

Branching Mechanics Recap

Before you jump into the practical exercises, let's do a quick recap of how Python handles conditional branching and code block alignment. Mastering how Python evaluates conditions and enforces indentation will prevent subtle bugs and keep your code readable.

Here is a quick refresher snippet demonstrating the full conditional structure:

score = 85

if score >= 90:
    print("Grade: A")
    print("Excellent work!")
elif score >= 80:
    print("Grade: B")
    print("Great job!")
else:
    print("Grade: C or lower")
    print("Keep practicing!")

Core Takeaways

Here is everything you need to remember about control flow mechanics before writing your own scripts:

  • Conditional structure sequence: Every conditional block starts with a mandatory if statement, can include any number of optional elif branches, and optionally ends with a single else fallback branch.
  • The colon syntax: You must end every if, elif, and else header line with a colon (:) to mark the start of a new execution block.
  • Indentation requirements: Python relies on whitespace typically 4 spaces to group statements inside a branch. Inconsistent spacing or missing indentation will trigger an IndentationError.
  • First-true-wins rule: Python checks conditions sequentially from top to bottom. It executes only the first branch whose expression evaluates to True and automatically skips every remaining branch in that chain.

Branching Structure Quick Reference

Keyword Role How Many Can You Use?
if Begins the conditional check Exactly 1 per chain
elif Evaluates secondary conditions if earlier checks fail 0 or more
else Executes default code if no prior conditions evaluate to True 0 or 1 (at the end)

With these core rules fresh in your mind, you are ready to tackle practical challenges!

Previous Lesson Next Lesson