Conditional branching is a fundamental concept in programming that allows a program to make decisions. It lets you execute specific blocks of code only if certain conditions are met, creating different "branches" or paths for the program to follow. The primary tools for this in Python are the if, elif, and else statements.
The conditions you test are built using comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not).
1. The if Statement
The if statement is the most basic control structure. It runs a block of code only if its condition evaluates to True. If the condition is False, the block of code is skipped entirely.
- Use Case: Executing an action only when a specific criterion is met. For example, sending a warning only if stock levels are low.
Python
# --- if Statement Example ---
stock_level = 8
# The code inside this block will only run if 'stock_level' is less than 10.
if stock_level < 10:
print("Warning: Stock level is low.")
# This line will run regardless of the condition.
print("Inventory check complete.")
2. The else Statement
The else statement provides an alternative block of code to execute if the if condition is False. It acts as a "catch-all" when the initial condition is not met.
- Use Case: Providing a default action when the primary condition isn't satisfied. For example, granting access if a password is correct, otherwise denying it.
Python
# --- if-else Statement Example ---
password_attempt = "12345"
if password_attempt == "correct_password":
print("Access Granted.")
else:
print("Access Denied.")
3. The elif Statement
elif is short for "else if." It allows you to check for multiple, mutually exclusive conditions in a sequence. Python will check each if and elif condition in order and will execute the first block it finds where the condition is True. If none are true, the else block (if present) will run.
- Use Case: Handling multiple specific cases before a general fallback. For example, assigning a letter grade based on a score.
Python
# --- if-elif-else Statement Example ---
score = 75
if score >= 90:
print("Grade: A")
# This is only checked if the first condition (score >= 90) was False.
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
# Output: Grade: C
4. Combining Conditions with Logical Operators
To build more complex logic, you use logical operators to combine multiple conditions.
- and Operator: The and operator returns True only if both conditions are True.
- Use Case: When multiple criteria must be met simultaneously, like checking if a user is old enough AND has a valid license to rent a car.
Python
age = 25
has_license = True
if age >= 25 and has_license:
print("Eligible to rent a car.")
else:
print("Not eligible.")
- or Operator: The or operator returns True if at least one of the conditions is True.
- Use Case: When any one of several criteria is sufficient, like giving a discount if a customer has a coupon OR is a premium member.
Python
has_coupon = False
is_premium_member = True
if has_coupon or is_premium_member:
print("Discount applied.")
else:
print("No discount.")
- not Operator: The not operator inverts the boolean value of a condition. not True becomes False, and not False becomes True.
- Use Case: Checking for the absence of a condition, which can often make code more readable.
Python
is_logged_in = False
if not is_logged_in:
print("Please log in to continue.")
5. Nested Conditional Statements
You can place if, elif, and else statements inside other conditional statements. This is called nesting and allows for more granular, hierarchical decision-making.
- Use Case: Handling situations where a decision depends on the outcome of a previous decision. For example, first checking if a user is logged in, and then checking their specific role.
Python
# --- Nested Conditionals Example ---
is_logged_in = True
user_role = "admin"
if is_logged_in:
print("Welcome, user!")
# This is a nested 'if' statement.
if user_role == "admin":
print("You have admin privileges.")
else:
print("You have standard user privileges.")
else:
print("Please log in to continue.")
6. The Ternary Operator (Conditional Expression)
This is a concise, one-line way to write a simple if-else statement. It's most useful for assigning a value to a variable based on a condition. The syntax is value_if_true if condition else value_if_false.
- Use Case: Quickly assigning one of two values to a variable.
Python
# --- Ternary Operator Example ---
age = 20
# Standard if-else
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(f"Status (using if-else): {status}")
# Powerful and concise Ternary Operator
status_ternary = "Adult" if age >= 18 else "Minor"
print(f"Status (using ternary): {status_ternary}")