3.1 if, elif, else Statements
Learning to make decisions in code with if, elif, and else structures, for creating conditional logic and executing different code blocks based on conditions.
The `if`, `elif` (which means "else if"), and `else` statements form the backbone of decision-making in programming. They allow you to execute different blocks of code depending on whether a specific condition is `True` or `False`.
The if Statement
It is the most basic control structure. The code block following the `if` will only be executed if the given condition is `True`. The syntax is: `if condition: # Code...`
The elif (else if) Statement
It is used when you want to check for multiple, mutually exclusive conditions. The code block following `elif` will be executed if the previous `if` (or `elif`) condition was `False` AND the current `elif` condition is `True`. You can have as many `elif` statements as you need.
The else Statement
It is optional and used as a "catch-all" case. The code block following `else` will be executed if all previous `if` and `elif` conditions were `False`.
"Truthy" and "Falsy" Values
In Python, conditions do not need to be strictly Boolean (`True`/`False`). Any value can be interpreted as "truthy" or "falsy". "Falsy" values are `None`, `False`, zero (`0`, `0.0`), empty collections (`""`, `[]`, `()`, `{}`), and empty sets. All other values are considered "truthy".
Nested if Statements
You can place an `if` statement inside another one. This is useful for more complex checks.
Ternary Operator
For simple `if-else` assignments in one line, you can use the ternary operator with the syntax: `value_if_true if condition else value_if_false`.
Tip!
Indentation is fundamental in Python. Every code block belonging to an `if`, `elif`, or `else` statement must have the same indentation (usually 4 spaces). Failure to follow this rule will result in an `IndentationError`.
# Example 1: Simple if statement
temperature = 28
if temperature > 25:
print("The temperature is high.")
print("-" * 30)
# Example 2: if-else
age = 19
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
print("-" * 30)
# Example 3: if-elif-else (Grade check)
grade = 75
if grade >= 90:
print("Excellent!")
elif grade >= 70:
print("Very good!")
elif grade >= 50:
print("Good.")
else:
print("You need to try harder.")
print("-" * 30)
# Example 4: Complex conditions with logical operators
is_user_logged_in = True
is_admin = False
if is_user_logged_in and is_admin:
print("Access as administrator.")
elif is_user_logged_in and not is_admin:
print("Access as a regular user.")
else:
print("Please log in.")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.