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
if Statement: The Simplest DecisionThe 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:
Python evaluates the condition
age >= voting_age.Since
19is greater than or equal to18, the condition isTrue.Because the condition is
True, Python executes the indented code block and prints "You are old enough to vote!".After the
ifblock 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
else Statement: Providing an AlternativeThe 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
elif Statement: Checking Multiple ConditionsSometimes 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:
Python first checks if
score >= 90. It'sFalse(85 is not >= 90).It moves to the next condition: is
score >= 80? It'sTrue.It executes the code for that
elifblock, printing "Grade: B".Crucially, once it finds a
Truecondition and runs its code, it skips the rest of theelifandelseblocks in that chain. Even thoughscore >= 70andscore >= 60are 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
if StatementsYou 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
ifstatement runs a block of code if a condition isTrue.The
elsestatement provides a fallback block to run if theifcondition isFalse.The
elifstatement 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!
Write a program that defines a variable
num. Use anif/elsestatement to print whether the number is positive or negative.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 asenior(True/False).Expand the grading program from the
elifexample. Add a check at the very beginning: if thescoreis greater than100or less than0, print an error message like "Invalid score".
Last updated