Control Flow: Making Decisions in Python with if
, elif
, and else
As a software engineer, I spend a lot of time telling computers what to do and when to do it. This is where control flow comes in handy - it’s the backbone of any programming language, allowing us to write code that does different things depending on certain conditions. Let’s dive into how Python makes decisions with if
, elif
, and else
statements!
What are if
, elif
, and else
?
-
if
: This is the basic decision-maker. It checks a condition, and if it’s true, executes a block of code.age = 25 if age >= 18: print("You are an adult.") else: print("You are not an adult.") # Example Output
elif
: This stands for “else if” and lets you check a second (or third, fourth, etc.) condition. It’s like saying “If the first condition isn’t met, let’s see if this other one applies.”
Python Code:
score = 85 if score >= 90: print("Excellent!") elif score >= 80: print("Good job!") else: print("Keep practicing!") # Output: Good Job! (if score is set to 85)
-
else if
: This statement allows you to check additional conditions after the initialif
statement. It’s a powerful tool for creating complex logic, as we’ll see in the examples below.Python Code:
# Example: Implementing a grading system score = 92 if score >= 90: grade = "A" print(f"Your grade is {grade}") elif score >= 80: grade = "B" print(f"Your grade is {grade}") # This line won't execute in this case. else: print("Keep practicing!") # Note that the 'else' part of the code will not be executed because the initial 'if' condition is already met by the first condition, # which checks for a score >= 90.
How does Python decide?
Let’s break down how Python uses these keywords in our grading example:
if
statement: Theif
statement acts like a checkpoint. It evaluates a condition (score >= 80
). In this case, since the first ‘if’ statement checks if the score is greater than or equal to 92 (and your code sets it to A), it will only print “Excellent!” and ignore theelif
statement entirely.else if
(orelif
) statements: These are like secondary checkpoints. If the initial condition of the ‘if’ statement doesn’t hold true, then Python checks the nextelif
statement down the line.
Common Mistakes
Here are some common mistakes I see when people first learn to use these keywords and how to avoid them:
- Forgetting to indent: Indentation is crucial in Python! Remember that code within an
if
,elif
, orelse
block needs to be indented. This tells Python which lines of code belong to the conditional statement. - Mixing up conditions: Make sure your
if
andelif
conditions are actually evaluating what you want them to.
Putting it All Together: Example
def grade_calculator(score):
"""Calculates a letter grade based on a numerical score."""
if score >= 90:
print("Your grade is A")
elif score >= 80:
print(f"You got an {score} - Your grade is A if the user entered 90 or above, and the code will only print 'Good job!' for this specific example. )
else:
print("Your score is below 90.")
grade_calculator(85) # This line will be executed because the score is 85 (which is greater than or equal to 90).
This example demonstrates how if
and elif
can be used together to create a more complex program.
- Python evaluates the conditions in order, from top to bottom.
- If the score is greater than or equal to 90, it will print ‘A’
Summary
This code will only print “Excellent!” if your grade is greater than 90 for the first condition and then print “Good job!” if the student scores a 80 or above, but less than 90. This allows Python to implement more complex decision-making by checking the conditions in order.
If you don’t use elif
correctly, your code might not work as expected because it will always skip to the next condition after the first one is met.
age = int(input("Enter the student's age: ")) # Assuming 'age' is a number in the input
if age >= 18:
print("You are an adult.")
elif age >= 17: # This condition will be evaluated only if the first one doesn't hold true.
print("Your score is below 90.") # This condition will only be checked if 'if' condition isn't true
- Example
# Example: Applying different scholarships based on score and age.
This if-else
structure helps us understand that a specific type of logic is required for the program to run correctly.