Chapter 5: Making Decisions - Control Flow with if, elif, and else

So far, our Python scripts have been like a straight road—they execute one line after another from top to bottom, without any detours. But what makes programming truly powerful is the ability to create roads that fork, allowing our programs to make decisions and take different paths based on certain conditions. This is called control flow.

In the last chapter, you learned how to use comparison and logical operators to create expressions that evaluate to True or False. Now, we'll use those boolean values to control the flow of our programs.

The if Statement: The Simplest Decision

The if statement is the most fundamental control flow tool. It allows you to run a block of code only if a certain condition is True.

The structure looks like this:

if some_condition:
    # Code to execute if some_condition is True
    # This block of code is indented

Let's look at a simple example:

age = 19
voting_age = 18

if age >= voting_age:
    print("You are old enough to vote!")

print("This line will always run, regardless of the condition.")

How it works:

  1. Python evaluates the condition age >= voting_age.

  2. Since 19 is greater than or equal to 18, the condition is True.

  3. Because the condition is True, Python executes the indented code block and prints "You are old enough to vote!".

  4. After the if block is finished, the program continues as normal and prints the final line.

If we changed age to 17, the condition age >= voting_age would be False, and the indented print statement would be skipped entirely.

The Importance of Indentation

Look closely at the example above. The line print("You are old enough to vote!") is indented. In Python, indentation is not just for readability; it's a rule. It's how Python knows which lines of code belong to the if statement.

The standard is to use four spaces for each level of indentation. Any code that is indented under the if statement will only run when the condition is True. The moment you stop indenting, you are "outside" the if block.

Python will immediately give you an IndentationError if you do this.

The else Statement: Providing an Alternative

The if statement is great for doing something when a condition is true, but what if you want to do something else when it's false? That's where the else statement comes in. It provides a block of code that runs when the if condition is False.

In this example, temperature > 25 is False. So, the code inside the if block is skipped, and the code inside the else block is executed instead. An else statement must always follow an if statement.

The elif Statement: Checking Multiple Conditions

Sometimes you have more than two possible paths. You could have a series of conditions you want to check one by one. For this, you can use elif, which is short for "else if".

An elif statement lets you add another condition to check if the first if condition was False. You can have as many elif statements as you need.

How this chain works:

  1. Python first checks if score >= 90. It's False (85 is not >= 90).

  2. It moves to the next condition: is score >= 80? It's True.

  3. It executes the code for that elif block, printing "Grade: B".

  4. Crucially, once it finds a True condition and runs its code, it skips the rest of the elif and else blocks in that chain. Even though score >= 70 and score >= 60 are also technically true, they are never checked.

The else at the end is a catch-all. It will only run if none of the preceding if or elif conditions were True.

Nested if Statements

You can also place control flow statements inside one another. This is called nesting. It allows for more complex logic.

Here, the inner if/else block (checking for a license) is only ever reached if the outer condition (age >= 18) is True.

Summary and What's Next

Congratulations, you've just learned how to make your programs smart! You can now control which parts of your code run and under what circumstances.

  • The if statement runs a block of code if a condition is True.

  • The else statement provides a fallback block to run if the if condition is False.

  • The elif statement allows you to check multiple conditions in a sequence.

  • Indentation is how Python groups blocks of code, and it is a mandatory rule.

You've moved from writing simple, straight-line scripts to programs that can reason and make decisions. This is a massive step in your programming journey!

The next logical step is to learn how to repeat actions without having to copy and paste code. In the next chapter, we'll dive into loops, which allow you to run a block of code over and over again.

Practice Time!

  1. Write a program that defines a variable num. Use an if/else statement to print whether the number is positive or negative.

  2. Create a program that checks if a user is eligible for a discount. The user gets a discount if they are a student (True/False) OR if they are a senior (True/False).

  3. Expand the grading program from the elif example. Add a check at the very beginning: if the score is greater than 100 or less than 0, print an error message like "Invalid score".

Last updated