Guard invalid or missing values
Validate request input or configuration before processing it.
Python · Const
Python’s if statement conditionally executes one suite. It checks the if and optional elif conditions in order, running the first matching suite or an optional else fallback.
An if statement evaluates its conditions from top to bottom. It executes only the suite belonging to the first true condition; if none is true, an optional else suite runs. Each suite is a colon-terminated, indented block.
if test1:
suite
elif test2:
suite
else:
suite| Name | Type | Description |
|---|---|---|
test / assignment_expression | expression | An expression whose truth value determines whether its suite is selected. |
suite | suite | The statement block executed when its associated condition is selected. |
if to run a block only when its condition is true.elif adds another condition-and-block alternative.else suite runs only when every if and elif condition is false.temperature = 22
if temperature < 0:
status = "freezing"
elif temperature == 0:
status = "freezing point"
else:
status = "above freezing"
print(status)Evaluates the conditions in order and prints the status for the first true condition.
Validate request input or configuration before processing it.
Choose behavior based on a state, role, or feature flag.
Provide a default action when no expected condition matches.
if statement to execute?The conditions are evaluated in order, and the suite associated with the first true condition runs. No other part of that if statement is executed or evaluated.
Follow-up: What happens when all conditions are false? If an else clause exists, its suite executes; otherwise, the statement performs no branch action.
elif and else?elif clauses provide additional conditions after the initial if, and an else clause is optional. The grammar permits zero or more elif clauses followed by at most one else clause.
Follow-up: Can an if statement have multiple else clauses? No; its grammar permits only an optional single else clause at the end.
if statement?The condition is an assignment_expression, followed by a colon and a suite. A suite is the block of statements controlled by that clause, normally written as an indented block.
Follow-up: Can suites be written on one line? Yes, Python permits a simple suite after the colon, though multiline indentation is generally clearer for substantial logic.
elifelsewhileforBoolean operationsconditional expression