Control Flow – if, elif, else in Python

Understanding decision-making in Python using conditional statements and comparison operators.

Welcome, fellow developers and aspiring programmers! In the vast landscape of software development, programs aren’t just a linear sequence of instructions. They need to be dynamic, adaptable, and capable of making intelligent decisions based on varying circumstances. This ability to choose different paths of execution is what we call “control flow,” and in Python, the primary tools for achieving this are the if, elif, and else statements.

This blog post is designed to complement our latest YouTube video and accompanying GitHub repository, offering a deep dive into Python’s decision-making constructs. We’ll explore how these statements, combined with powerful comparison and logical operators, empower your code to react smartly to input and conditions.

What is Control Flow? The Brain of Your Program

Imagine your daily life: “If it’s raining, I’ll take an umbrella; otherwise, I’ll walk.” Or a cooking recipe: “If you have butter, use it; else, use oil.” These are everyday decisions. In programming, control flow is precisely this: the process of determining which code blocks to execute based on specific conditions. Without it, your Python programs would simply run from top to bottom, executing every line regardless of context. This would severely limit their functionality and responsiveness.

Control flow statements transform your rigid script into a flexible, intelligent, and interactive application. They allow your program to branch out, skip sections, or repeat actions, providing the responsiveness needed for real-world applications.

The if Statement: The Single Gatekeeper

Our journey begins with the simplest yet most fundamental conditional statement: the if statement. It acts as a gatekeeper, allowing a block of code to execute *only if* a specified condition evaluates to True. If the condition is False, the entire indented block of code associated with the if statement is skipped.

Consider the temperature example from our accompanying main.py script:

temperature = 28
if temperature > 25:
    print(f"It's {temperature}°C. It's a hot day!")
print("The weather observation for this example is complete.")
    

Here, since 28 > 25 is True, the message “It’s 28°C. It’s a hot day!” will be printed. If temperature was, say, 20, the condition would be False, and that specific print statement would be ignored, with the program moving directly to the final line.

The if-else Statement: The Fork in the Road

What if you want your program to perform one action if a condition is true, and a *different* action if it’s false? The if-else statement provides exactly this: two distinct execution paths. One block of code is guaranteed to execute, providing a clear binary decision.

Our main.py demonstrates this with an age check:

user_age_str = input("Enter your age: ")
try:
    user_age = int(user_age_str)
    if user_age >= 18:
        print("You are an adult.")
    else:
        print("You are a minor.")
except ValueError:
    print("Invalid age entered. Please enter a number.")
    

If the user enters 20, user_age >= 18 is True, and “You are an adult.” prints. If they enter 15, the condition is False, and the program jumps to the else block, printing “You are a minor.” This construct ensures a response for every valid input.

The if-elif-else Statement: Cascading Decisions

For scenarios requiring more than two outcomes, the if-elif-else chain is your go-to. This powerful structure allows you to check a sequence of conditions. Python evaluates each condition in order: the initial if, then subsequent elif (short for “else if”) statements. The first condition that evaluates to True will have its corresponding code block executed, and the rest of the chain (including any remaining elifs and the final else) is completely skipped. If none of the if or elif conditions are met, the optional else block at the very end acts as a fallback.

Think of a grading system, as illustrated in our example code:

score_str = input("Enter your test score (0-100): ")
try:
    score = int(score_str)
    if score >= 90:
        print("Grade: A (Excellent work!)")
    elif score >= 80:
        print("Grade: B (Very good!)")
    elif score >= 70:
        print("Grade: C (Good effort.)")
    elif score >= 60:
        print("Grade: D (Pass.)")
    else:
        print("Grade: F (Needs improvement.)")
except ValueError:
    print("Invalid score entered. Please enter a number.")
    

If the score is 95, it’s an ‘A’, and no other elif or else is checked. If it’s 75, the first two conditions are False, but score >= 70 is True, so it prints ‘C’, and the rest are skipped.

Behind the Decisions: Comparison Operators

How do if, elif, and else statements know if a condition is True or False? This is where Boolean logic and comparison operators come into play. Every condition you write ultimately evaluates to one of two fundamental values: True or False (these are special built-in Python values, known as Booleans). Comparison operators are the tools that produce these Boolean results by comparing two values.

Here are the common comparison operators used in Python, as demonstrated in main.py:

  • == (Equal to): Checks if two values are exactly the same. (e.g., 5 == 5 is True, 'hello' == 'world' is False). **Crucially, do not confuse with =, which is for assignment.**
  • != (Not equal to): Checks if two values are different. (e.g., 10 != 7 is True).
  • < (Less than): Checks if the left value is strictly smaller than the right. (e.g., 3 < 8 is True).
  • > (Greater than): Checks if the left value is strictly larger than the right. (e.g., 12 > 5 is True).
  • <= (Less than or equal to): Checks if the left value is smaller than or equal to the right. (e.g., 4 <= 4 is True, 3 <= 4 is True).
  • >= (Greater than or equal to): Checks if the left value is larger than or equal to the right. (e.g., 7 >= 7 is True, 9 >= 6 is True).

Building Complex Logic: Logical Operators

Beyond simple comparisons, you often need to evaluate multiple conditions simultaneously. This is where logical operators—and, or, and not—become indispensable. They allow you to combine Boolean expressions to form highly complex conditions.

  • and: Both Must Be True
    The and operator requires *both* conditions it connects to be True for the entire expression to be True. If even one condition is False, the whole and expression evaluates to False. Think of it like needing both keys to open a locked door.

    is_sunny = True
    is_warm = False
    if is_sunny and is_warm: # This is (True and False), which evaluates to False
        print("It's sunny AND warm today. Perfect beach weather!")
    else:
        print("It's not both sunny AND warm.")
                

    In this example, the else block will execute because is_warm is False.

  • or: At Least One Must Be True
    The or operator is more permissive. For an or expression to be True, only *at least one* of the conditions it connects needs to be True. It only evaluates to False if *both* conditions are False. You can enter a building if you have a Student ID OR an Employee Badge.

    is_sunny = True
    is_warm = False
    if is_sunny or is_warm: # This is (True or False), which evaluates to True
        print("It's either sunny OR warm (or both). Good for outdoor activities!")
    else:
        print("It's neither sunny nor warm.")
                

    Here, the if block executes because is_sunny is True.

  • not: Inverts the Truth
    The not operator is a unary operator, meaning it operates on a single Boolean expression. It simply inverts the truth value of the condition it precedes: True becomes False, and False becomes True. It’s like flipping a switch.

    has_hat = True
    if not has_hat: # This is (not True), which evaluates to False
        print("You might need a hat if it's sunny!")
    else:
        print("You have a hat, good for sun protection!")
                

    Because has_hat is True, not has_hat becomes False, so the else block is executed.

Combining Operators for Sophisticated Logic

You can combine comparison and logical operators, using parentheses to define the order of evaluation (just like in mathematics). This allows for highly specific and powerful decision rules:

is_sunny = True
money_in_wallet = 35
is_warm = False
has_hat = True

if (is_sunny and money_in_wallet >= 30) or (is_warm and not has_hat):
    print("Consider a nice outdoor treat or a new hat!")
else:
    print("Staying indoors seems fine for now.")
    

This single condition checks if (it’s sunny AND you have enough money) OR (it’s warm AND you don’t have a hat). Python evaluates the conditions within parentheses first, then applies the or logic, leading to precise outcomes.

Best Practices for Writing Conditional Logic

As you craft your own conditional logic, keep these best practices in mind for robust and readable code:

  • Indentation is Key: In Python, indentation defines code blocks. Consistent and correct indentation is non-negotiable for your programs to run correctly.
  • Clear Naming & Comments: Use meaningful variable names (e.g., user_age instead of x) and add comments for complex logic. Your future self (and others!) will thank you.
  • Order Matters in if-elif-else: Place the most specific or most likely conditions first. Python stops evaluating once it finds a True condition, which can sometimes impact performance or prevent unintended outcomes if conditions overlap.
  • Error Handling with try-except: As shown in our examples, always anticipate unexpected user input. Wrapping user input conversion (e.g., int(input_str)) in a try-except ValueError block prevents your program from crashing if a user types text instead of a number. This makes your applications more resilient and user-friendly.

How to Use the Accompanying Code

The provided code in our GitHub repository, specifically main.py, offers interactive examples that demonstrate all the concepts discussed here. It’s designed to let you experiment and see these principles in action.

To run the code:

  1. Ensure you have Python installed (version 3.6 or higher recommended).
  2. Download or clone the repository from GitHub.
  3. Navigate to the PythonFlowControl directory in your terminal or command prompt.
  4. Run the script using the Python interpreter:
    python main.py

The script will prompt you for input and show you how different conditional blocks are executed based on your responses, reinforcing your understanding of decision-making in Python.

Watch the Video & Explore the Code!

To deepen your understanding and see these concepts demonstrated visually, watch our full video tutorial:

And don’t forget to explore the source code directly on GitHub. Fork the repository, experiment with the examples, and even contribute your own variations!

Explore the Code on GitHub

Conclusion

Mastering control flow is an indispensable skill for any Python programmer. From the foundational if statement to the versatile if-elif-else chains, and through the powerful world of comparison (==, !=, <, >, <=, >=) and logical operators (and, or, not), you now have the tools to make your Python applications intelligent, responsive, and dynamic. Keep experimenting, keep coding, and remember that every decision your program makes brings it closer to its full potential. Happy coding!

Posted in

Leave a Reply