Python if, elif, and else statements control execution flow by evaluating expressions to True or False.
Branching & Flow Control: When an if condition tests true, its indented block runs and subsequent checks are skipped. Combine conditions using logical operators (and, or, not), compress simple assignments into ternary expressions, control execution cycles inside for loops and while loops, or stub pending logic with the pass statement. To assign academic marks, see our student grade script.
if-elif-else LogicPython relies on strict indentation (typically four spaces) to define code blocks executed under an if, elif, or else branch:
# Formal syntax of Python if-elif-else statements
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
fallback_statement_block
In this basic example, Python checks whether mark >= 50. If true, the indented status = "Pass" block executes; otherwise, execution shifts to the else block:
# 1. Basic if-else condition check
mark = 60
if mark >= 50:
status = "Pass"
else:
status = "Fail"
print("Exam result:", status)Terminal Output:
Exam result: Pass
When multiple mutually exclusive conditions exist, use elif (short for "else if") to test subsequent conditions sequentially as soon as the preceding test evaluates to False:
# 2. Using elif for multi-tier branch evaluation
x = 10
y = 20
if x > y:
print("x is greater than y")
elif y > 15:
print("y is greater than 15")
else:
print("y is greater than x but less than 15")Terminal Output:
y is greater than 15
Understanding when to chain elif vs terminating with else prevents redundant computations:
| Feature | elif (Else If) |
else (Fallback) |
|---|---|---|
| Condition Required? | Yes — Requires a boolean condition to evaluate. | No — Takes no condition; catches all remaining cases. |
| Frequency | Can appear 0, 1, or multiple times in a chain. | Can appear at most once, strictly at the end of the chain. |
| Evaluation Trigger | Evaluated only if preceding if or elif tests evaluated to False. |
Executes only if every preceding condition evaluated to False. |
| Execution Circuit | Stops checking subsequent branches once matched. | Terminal block; marks the absolute conclusion of the conditional block. |
Avoiding Redundant Evaluations: Chaining with elif ensures Python halts testing as soon as the first matching condition evaluates to True. If you write independent if statements instead, Python tests every statement sequentially, wasting CPU cycles and risking conflicting mutations.
For concise assignments, Python supports conditional ternary expressions (x if condition else y):
# 3. Short syntax and single-line ternary expressions
x = 10
y = 20
# Single-line if statement
if y > x: print("y is greater than x")
# Ternary if-else expression: value_if_true if condition else value_if_false
status = "Pass" if x >= 50 else "Fail"
print("Ternary status: ", status)
# Ternary print invocation
print("y is big") if y > x else print("x is big")Terminal Output:
y is greater than x
Ternary status: Fail
y is big
You can also use ternary expressions inside user-defined functions to build concise predicates:
# 5. User-defined function returning ternary boolean
def is_even(num: int) -> bool:
return True if num % 2 == 0 else False
print("Is 14 even? ", is_even(14))
print("Is 21 even? ", is_even(21))Terminal Output:
Is 14 even? True
Is 21 even? False
Python allows chaining multiple comparison operators together, reading like natural mathematical notation:
# 4. Chained comparison operators (Pythonic range checking)
score = 85
# Evaluates equivalent to (80 <= score) and (score <= 100)
if 80 <= score <= 100:
print("Grade A achieved!")Terminal Output:
Grade A achieved!
Calculating the absolute value of a number using a simple condition:
# 6. Absolute value calculation via condition check
num = -25
if num < 0:
num = -num
print("Absolute value is:", num)Terminal Output:
Absolute value is: 25
Conditional statements can be nested inside one another to solve multi-variable ordering and classification problems:
# 7. Nested conditional branching: Sorting three numbers
n1 = 15
n2 = 42
n3 = 28
if n1 >= n2 and n1 >= n3:
if n2 >= n3:
print("Descending:", n1, n2, n3)
else:
print("Descending:", n1, n3, n2)
elif n2 >= n1 and n2 >= n3:
if n1 >= n3:
print("Descending:", n2, n1, n3)
else:
print("Descending:", n2, n3, n1)
else:
if n1 >= n2:
print("Descending:", n3, n1, n2)
else:
print("Descending:", n3, n2, n1)Terminal Output:
Descending: 42 28 15
Combine multiple truth tests using Python's logical operators:
# 8. Boolean compound logic with and, or, not
temperature = 30
is_sunny = True
is_weekend = False
is_holiday = True
# Logical and (both conditions must be True)
if temperature > 25 and is_sunny:
print("Weather condition: Hot and sunny")
# Logical or (at least one condition must be True)
if is_weekend or is_holiday:
print("Schedule status: Non-working day")
# Logical not (inverts boolean truth value)
weather_is_good = False
if (is_weekend or is_holiday) and not weather_is_good:
print("Activity plan: Stay indoors and read")Terminal Output:
Weather condition: Hot and sunny
Schedule status: Non-working day
Activity plan: Stay indoors and read
Conditions are frequently placed inside for loops and while loops to filter data, skip iterations with continue, or terminate early with break:
# 9. Conditional checking inside a loop with break and continue
print("Inspecting loop values:")
for x in range(5, 30, 5):
if x == 15:
print("-> Value 15 reached: skipping with continue")
continue
if x == 25:
print("-> Value 25 reached: terminating with break")
break
print("Current x:", x)Terminal Output:
Inspecting loop values:
Current x: 5
Current x: 10
-> Value 15 reached: skipping with continue
Current x: 20
-> Value 25 reached: terminating with break
In Python, empty collections ([], {}, ""), zero (0), and None evaluate to False in boolean contexts:
# 10. Handling None and truthy/falsy evaluation
val_none = None
empty_list = []
active_user = "Alex"
if val_none:
print("val_none is truthy")
else:
print("val_none evaluates to False")
if not empty_list:
print("empty_list is falsy (len == 0)")
if active_user:
print("User authenticated:", active_user)Terminal Output:
val_none evaluates to False
empty_list is falsy (len == 0)
User authenticated: Alex
Because Python code blocks cannot be empty, use the pass statement as a placeholder when architecting branch skeletons:
# 11. The pass statement in placeholder conditional blocks
age = 15
if age < 18:
# Future feature: send underage parental notification
pass
else:
print("Access granted: Adult account")
print("Program continued smoothly past pass block.")Terminal Output:
Program continued smoothly past pass block.
Practice conditional branching, ternary expressions, chained comparisons, and nested sorting in our interactive companion Jupyter Notebook:
Explore interactive code cells, test short-circuit logic, solve student grade assignments, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify conditional evaluation mechanics:
# 12. Self-verifying unit test suite for if-else control flow
# Test 1: Ternary pass/fail evaluation
score = 75
result = "Pass" if score >= 50 else "Fail"
assert result == "Pass"
# Test 2: Chained comparison logic
val = 88
assert (80 <= val <= 100) is True
# Test 3: Boolean short-circuiting
def trigger_error():
raise RuntimeError("Should not be called!")
# With 'or', if first operand is True, second is never evaluated:
assert (True or trigger_error()) is True
# With 'and', if first operand is False, second is never evaluated:
assert (False and trigger_error()) is False
# Test 4: Truthy and Falsy conversions
assert bool(None) is False
assert bool([]) is False
assert bool("Python") is True
print("All if-else condition assertion checks successfully verified!")Terminal Output:
All if-else condition assertion checks successfully verified!
Yes. An if statement is completely valid on its own. The else and elif blocks are strictly optional.
Starting in Python 3.10+, Python includes the match-case structural pattern matching statement, which acts as a powerful alternative to long elif chains.
In and operations, if the first operand is False, Python stops evaluating. In or operations, if the first operand is True, Python immediately returns without evaluating the second operand.
Constants None and False, zero of any numeric type (0, 0.0), empty sequences ("", (), []), and empty mappings ({}).
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.