Mastering Conditional Branching with Python's if Statement
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you havenโt installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
Welcome to the world of programming! For all you beginners who have just started creating websites or developing apps, how is your Python journey going? This time, we're going to do a deep dive into the if statement, one of the fundamental "control structures" in programming. The if statement is a command that executes a process only when a specific condition is met, allowing you to create conditional branches like, "if this is true, then do that." By reading this article, you'll gain a solid understanding of the if statement from basics to applications, and experience the "joy of seeing your code work" with examples you can copy and paste!
Basic Usage of the if Statement
First, let's look at the simplest form of an if statement. This is for when you want to say, "if a condition is true, execute the code inside." The syntax is very simple.
if condition:
# Code to be executed when the condition is True
What's important here are the colon (:) and the indentation. You must always put a colon at the end of the if statement line, and the code you want to execute is indented (usually with four spaces) on the next line. This indentation plays a crucial role in defining code blocks in Python.
Now, let's see some code in action. Here's a simple example that checks if an age is 20 or older.
# Assign 25 to the variable 'age'
age = 25
# If age is 20 or greater, print a message
if age >= 20:
print("You are an adult.")
# This line is outside the if block, so it always runs regardless of the condition
print("Program finished.")
Execution Result:
You are an adult.
Program finished.
In this code, the variable `age` is 25, so the condition `age >= 20` becomes true. Therefore, the indented `print("You are an adult.")` is executed. If you change the value of `age` to something like 18 and run it, this line will not be executed, and only "Program finished." will be displayed. Go ahead and try it!
else: Handling When the Condition Is Not Met
Next, let's learn how to add a process for when the condition is not met, as in "if this is true, do A; otherwise, do B." This is where else comes in.
if condition:
# Code to be executed when the condition is True
else:
# Code to be executed when the condition is False
Let's add an else to our previous age-checking example. This time, we'll set `age` to 18.
# Assign 18 to the variable 'age'
age = 18
# If age is 20 or greater, print "You are an adult."
if age >= 20:
print("You are an adult.")
# Otherwise, print "You are a minor."
else:
print("You are a minor.")
print("Program finished.")
Execution Result:
You are a minor.
Program finished.
This time, `age` is 18, so the condition `age >= 20` is false. Therefore, the code in the if block is skipped, and the code inside the else block, `print("You are a minor.")`, is executed. Now, no matter what age is entered, one of the two messages will always be displayed.
elif: Branching with Multiple Conditions
So, what if you have more than two conditions? For example, you might want to assign grades like "Excellent," "Good," "Pass," or "Fail" based on a score. For such multiple conditional branches, you use elif (short for else if).
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition1 is False and condition2 is True
elif condition3:
# Code to be executed if conditions 1 and 2 are False, and condition3 is True
else:
# Code to be executed if all conditions are False
You can add as many elif statements as you need. Python evaluates the conditions from top to bottom and, once it finds a condition that is true, it executes that block of code and then skips the rest of the elif and else blocks, exiting the entire if statement.
Let's look at a grade evaluation example.
# Assign a score of 85 to the variable 'score'
score = 85
if score >= 90:
grade = "Excellent"
elif score >= 80:
grade = "Good"
elif score >= 60:
grade = "Pass"
else:
grade = "Fail"
print(f"Your score is {score}, so your grade is '{grade}'.")
Execution Result:
Your score is 85, so your grade is 'Good'.
In this code, `score` is 85.
- The first condition, `if score >= 90:`, is false.
- The next condition, `elif score >= 80:`, is true.
Advanced Example: Combining Multiple Conditions
In an if statement, you can also use logical operators like `and`, `or`, and `not` to specify more complex conditions.
- `A and B`: True only if both A and B are true.
- `A or B`: True if at least one of A or B is true.
- `not A`: True if A is false.
For example, let's write a condition for "between 9 AM and 5 PM, and not a weekend."
# Simulate the current time and day of the week
hour = 10
day_of_week = "Monday"
# Check business hours
# Hour is 9 or greater AND less than 17
is_open_hour = hour >= 9 and hour < 17
# Day is not Saturday AND not Sunday
is_weekday = day_of_week != "Saturday" and day_of_week != "Sunday"
if is_open_hour and is_weekday:
print("We are open.")
else:
print("We are closed.")
Execution Result:
We are open.
By combining multiple conditions like this, you can express more complex, real-world rules in your programs.
A Complete Example for Web Creators
As web creators, you might be interested in using Python to dynamically generate HTML. The following example is a Python script that generates an HTML message based on a user's login status and membership plan. Running this Python code will create an HTML file named `welcome_message.html`. This is a perfect opportunity to experience code that "just works"!
Try saving the following Python code as a file, for example `generate_html.py`, and running it.
# --- User Information Simulation ---
is_logged_in = True
user_name = "Smith"
membership_plan = "premium" # can be "premium", "standard", or "free"
# --- Determine HTML Content ---
if is_logged_in:
if membership_plan == "premium":
title = f"Welcome, {user_name}"
message = "You have access to all premium features."
color = "#ffd700" # Gold
elif membership_plan == "standard":
title = f"Welcome, {user_name}"
message = "You are currently on the standard plan."
color = "#4682b4" # SteelBlue
else: # free plan
title = f"Welcome, {user_name}"
message = 'You are using the free plan. Would you like to upgrade?'
color = "#cccccc" # LightGray
else:
title = "Hello, Guest"
message = 'You need to log in to use our services.'
color = "#f0f0f0"
# --- Generate HTML Code ---
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome Message</title>
<style>
body {{
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f9f9f9;
}}
.welcome-card {{
border: 2px solid {color};
border-radius: 10px;
padding: 2rem;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
text-align: center;
background-color: white;
}}
h1 {{
color: #333;
}}
p {{
color: #555;
font-size: 1.1rem;
}}
a {{
color: #007bff;
text-decoration: none;
}}
a:hover {{
text-decoration: underline;
}}
</style>
</head>
<body>
<div class="welcome-card">
<h1>{title}</h1>
<p>{message}</p>
</div>
</body>
</html>
"""
# --- Write to File ---
try:
with open("welcome_message.html", "w", encoding="utf-8") as f:
f.write(html_content)
print("Generated 'welcome_message.html'.")
print("Please open it in a browser to check.")
except IOError as e:
print(f"An error occurred while writing the file: {e}")
After running this code, a file named `welcome_message.html` will be created in the same folder. When you open this file in a browser, you should see a styled message that changes based on the values of `is_logged_in` and `membership_plan`. Try changing the values of these variables to see how the generated HTML changes! This is the first step toward creating dynamic content with programming.
Points to Note (Common Mistakes)
There are a few common mistakes that everyone makes when they first start using if statements. Let's check them beforehand.
1. Confusing the Equality Operator `==` with the Assignment Operator `=`
To compare if two values are "equal" in an if statement's condition, you must use two equal signs `==`. A single equal sign `=` is the assignment operator, used for assigning a value to a variable. Mixing these up will cause errors or unexpected behavior.
# Wrong
if membership_plan = "premium": # This will cause an error!
...
# Correct
if membership_plan == "premium":
...
2. Indentation Errors
In Python, indentation defines the code's structure itself. The code inside an if block must be indented with the same number of spaces (usually four). If the indentation is inconsistent, you will get an `IndentationError`.
score = 80
if score >= 60:
print("You passed.")
print("Congratulations.") # Error due to incorrect indentation
3. Distinguishing Between `if` and `elif`
If you just list multiple conditions using only `if`, each `if` statement will be evaluated independently. This can lead to results you didn't intend.
For example, let's consider a case where the score is 95.
# Wrong example (using consecutive ifs)
score = 95
if score >= 90:
print("The grade is Excellent.")
if score >= 80: # This if is also evaluated independently
print("The grade is Good.")
Execution Result:
The grade is Excellent.
The grade is Good.
Since 95 is both greater than or equal to 90 and greater than or equal to 80, both messages were displayed. This is exactly where `elif` comes in handy. If you use `elif`, the evaluation stops as soon as a condition is met.
# Correct example (using elif)
score = 95
if score >= 90:
print("The grade is Excellent.")
elif score >= 80:
print("The grade is Good.")
Execution Result:
The grade is Excellent.
Thus, when you want to evaluate a single item against multiple tiered conditions, using the `if-elif-else` structure is appropriate.
Introduction to Related Useful Code
Let's also introduce some convenient syntax that is often used with if statements.
The `in` Operator: Check if an Element is in a List or String
When you want to check if a specific element is contained within a list, tuple, or string, the `in` operator is extremely useful. It allows you to write much more concise code than chaining many `or` conditions.
For example, let's check if today's day of the week is a holiday (Saturday or Sunday).
day_of_week = "Sunday"
holidays = ["Saturday", "Sunday"]
# Verbose way
# if day_of_week == "Saturday" or day_of_week == "Sunday":
# print("It's a day off today.")
# Smart way using the 'in' operator
if day_of_week in holidays:
print("It's a day off today.")
else:
print("It's a work day today.")
Execution Result:
It's a day off today.
Using the `in` operator, you can check if `day_of_week` is included in the `holidays` list in a single line, making the code much easier to read.
Summary
In this article, we've covered the basics of conditional branching in Python using the if statement, from its fundamental usage to applications with `else` and `elif`, and even a concrete HTML generation example for web creators.
- if: Executes code when a condition is true.
- else: Executes code when the if condition is false.
- elif: Evaluates multiple conditions in sequence.
- Indentation and the colon (:) are key to the syntax.
- You can express more complex conditions by combining operators like `and`, `or`, and `in`.
The if statement is a critically important structure used in all kinds of programs. Try running the code from this article on your own machine, and experiment by changing the values. By seeing your own code change its behavior based on conditions, you'll be able to feel the fun and power of programming. Master conditional branching and apply it to the web services and tools you want to create!
As a next step, why not learn about loops?
To the next article: Understanding Loops with Python's for and while Statements