While a standalone if statement provides a one-way branch, real-world programming frequently demands two-way decision making: do action A if a condition is met; otherwise, do action B. The if-else statement guarantees that exactly one of the two execution blocks will run.
if condition:
# Executes when condition is True
statement_block_1
else:
# Executes when condition is False
statement_block_2
number = 27
if number % 2 == 0:
print(f"{number} is an EVEN number.")
else:
print(f"{number} is an ODD number.")
Python provides an elegant inline syntax to assign values based on a condition:
# Syntax: result = x if condition else y
marks = 68
status = "PASSED" if marks >= 40 else "FAILED"
print("Examination Status:", status)
# Finding maximum of two numbers:
a, b = 45, 78
max_val = a if a > b else b
print("Maximum:", max_val)
else statement cannot stand alone; it must always be paired with a preceding if, for, while, or try block.