Conditional execution
As programs grow beyond straight-line execution, they need a way to make decisions. Conditional execution is how a Python program chooses one path over another based on the current state of its data. This is a foundational skill for building programs that react to input, data, or environment—whether that means generating different pages, selecting actions, or controlling larger workflows.
The purpose of conditional execution
Conditional execution lets a program decide whether a block of code should run. Instead of always executing every line from top to bottom, the program evaluates a condition and proceeds only if that condition is true. This allows us to express simple rules and decision points directly in code.
The basic if statement
The simplest form of conditional execution in Python uses the if statement. An if statement evaluates a Boolean expression and executes a block of code only when that expression is true.
has_rings = True
if has_rings:
print("This planet has rings.")
If the condition evaluates to False, the indented block is skipped and execution continues with the next statement after it.
Executing code blocks based on conditions
An if statement controls a block of code, not just a single line. Any statements indented under the if belong to that conditional block and run together when the condition is satisfied.
planet_name = "Saturn"
has_rings = True
if has_rings:
print(planet_name)
print("is known for its rings.")
All indented statements are treated as a unit and are either all executed or all skipped.
Using elif and else for multiple branches
When there are multiple possible outcomes, Python provides elif (else if) and else. These allow the program to choose exactly one branch from several alternatives.
moons = 0
if moons == 0:
print("This planet has no moons.")
elif moons == 1:
print("This planet has one moon.")
else:
print("This planet has multiple moons.")
The conditions are checked from top to bottom. The first matching branch is executed, and the rest are ignored.
How indentation defines conditional blocks in Python
Python uses indentation to define which statements belong to an if, elif, or else block. There are no braces or keywords to mark the start and end of a block—indentation is the structure.
temperature = -150
if temperature < 0:
print("Below freezing")
print("Condition check complete")
Only the indented line is conditional. The final print runs regardless of the condition. Consistent indentation is essential, because it directly controls program behavior.
Conclusion
With if, elif, and else, we can express decisions directly in Python code. We now know how a program can execute different blocks based on conditions, and how indentation defines the scope of those decisions. This gives us the tools to move beyond linear scripts and start writing programs that respond intelligently to data and state.