liveBook · Manning

Else clause

As explained in Get Programming: Learn to code with Python

An else clause is an optional alternative branch that executes when preceding conditions are false or protected code completes without an exception.

An else clause is the final alternative in an if-elif-else decision. It runs when none of the preceding conditions is true; only the first matching branch runs. section 14.2

Listing 14.3. Example of a simple if-elif-else conditional statement
num = int(input("Enter a number: "))                #1
if num > 0:                                         #2
    print("num is positive")                        #3
elif num < 0:                                       #4
    print("num is negative")                        #5
else:                                               #6
    print("num is zero")                            #7

The number check shows else handling the remaining case: when a number is neither positive nor negative, it prints that the number is zero. section 14.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains branch selection and optional else clauses, stopping short of implementation internals.
Examples
Demonstrates classifying an input number as positive, negative, or zero.
What it assumes
Assumes familiarity with writing a conditional statement and introduces how elif and else extend it.
What you can do after
Apply if-elif-else branches to choose one code block based on conditions.
How it connects
Connects else clauses to if statements, elif clauses, and conditional statements.

Also explained in

Compare how 5 books explain else clause →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.