Provide a default path when no `if` or `elif` condition matches.
Conditional branching
Python · Const
else supplies a fallback or successful-completion branch in Python compound statements. Its meaning depends on whether it follows if, a loop, or try.
else is a clause used with conditional statements, loops, and try. Its behavior depends on the construct: it handles the no-match path for if, normal completion for loops without break, and successful completion of a try suite without an exception or early loop-control statement.
if_stmt ::= "if" expression ":" suite ("elif" expression ":" suite)* ["else" ":" suite]
while_stmt ::= "while" expression ":" suite ["else" ":" suite]
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]
try_stmt ::= ("try" ":" suite ("except" [expression ["as" target]] ":" suite)+ ["else" ":" suite] ["finally" ":" suite] | "try" ":" suite ["finally" ":" suite])if chain, else is the fallback suite when all tested conditions are false.if/elif chain executes at most one selected suite.while loop, else runs when the condition becomes false and the loop ends normally.try statement's else suite is optional and is considered after control leaves the try suite.try else suite requires no exception and no early exit from the try suite.try statement's else suite is not caught by that statement's preceding except clauses.for item in [1, 3, 5]:
if item % 2 == 0:
print("found")
break
else:
print("no even item")The loop's else suite runs because the loop finishes without executing break.
Conditional branching
Search loops
Validated operations
else clause?In an if statement, else runs only when every preceding condition is false. In a loop, it runs when the loop completes normally: a for loop is exhausted or a while condition becomes false.
Follow-up: How can a loop search use else? Put break in the match branch; the else suite then represents the no-match path because it runs only when no break occurs.
else on try?A try else suite runs after the try suite completes without an exception and without return, continue, or break. It is therefore useful for code that should run only after the protected operation succeeds.
Follow-up: Are exceptions in the try else suite caught by the preceding except clauses? No; those handlers apply to the preceding try suite, not to the else suite.
else work with if and elif?The if form selects one suite after evaluating conditions in order; if none is true, the else suite runs. Only the selected suite executes, so later branches are not evaluated or executed.
Follow-up: Can an if statement omit else? Yes. The else clause is optional, and with no matching condition no fallback suite executes.
if statementeliffor statementwhile statementtry statementexcept clause