Conditional Statement
A conditional statement chooses which code runs. if evaluates a condition and runs its block when the result is true. elif tests a further condition only when every earlier test was false, and else covers the remaining cases. This is branching: one path through the code is selected from several.
Each branch header ends with a colon. Python marks blocks with indentation rather than braces; four spaces per level is the usual style. The lines belonging to a branch are indented consistently, and the if, elif, and else keywords of one statement align with each other. Mixing tabs and spaces, or indenting by different amounts, changes which lines belong to the branch or raises IndentationError.
At most one branch of a chain runs: Python takes the first condition that is true and skips the rest. Test order is therefore part of the logic, and a broad condition placed first hides the narrower ones below it. Writing separate if statements instead of elif means several of them can run, which is a different result. For mutually exclusive alternatives, an elif chain is often clearer; checks that depend on an earlier branch may need nesting.
else is optional. Without it, a value that matches no condition leaves earlier state untouched, which is a common way for a stale value to survive into the output; if the name was never assigned, reading it instead raises NameError. An explicit else that sets a default or reports the unexpected case makes that visible. When a condition only selects between two values, the conditional expression a if condition else b can replace the statement, but a branch that does real work belongs in a full statement.
Further reading
See the worked examples in Python Strings, Conditions, and Loops.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
