liveBook · Manning

Elif clause

As explained in Get Programming: Learn to code with Python

elif is a Python keyword that introduces an alternative condition checked only when preceding conditions are false.

An elif clause introduces another condition after if. Python checks it only when earlier conditions are false, then runs the first block whose condition is true. 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

A number checker combines if, elif, and else: positive numbers print one message, negative numbers another, and zero uses the final alternative. section 14.2

Remember these rules:

  • Begin the decision chain with if; add one or more elif clauses when later conditions are needed. section 14.2
  • Only one branch runs, even when several conditions might eventually be true; Python stops at the first true condition. section 14.2
  • Use separate if statements when multiple independent actions should run rather than one exclusive choice. section 14.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains syntax, branch order, variations, and contrasts with separate if statements through small examples.
Examples
Uses number classification, sign checking, greetings, language selection, and nested number choices.
What it assumes
Assumes familiarity with basic if statements and conditional expressions.
What you can do after
Apply it via Python conditional chains that select one appropriate action.
How it connects
Connects elif clauses with conditional statements, if clauses, else clauses, nested conditionals, and Boolean conditions.

Also explained in

Compare how 3 books explain elif 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.