LearnWave
Learn it. Master it.

Flow of Control

elif, nested if and indentation

Write a chain of if, elif and else.

When there are more than two possibilities, use if..elif..else. Python checks the conditions in order. The first one that is true runs its block, and all the rest are skipped. If none is true, the else block runs. For example:

  • if num > 0: print("Positive")
  • elif num < 0: print("Negative")
  • else: print("Zero")

You can have as many elif blocks as there are conditions to check. A traffic signal program, for example, prints STOP for red, Be Slow for yellow, and Go! for green, each in its own branch.

An if..else can be placed inside another if or elif block. This is a nested if. In the book's calculator program (Program 6-3), for subtraction, an inner if..else subtracts the smaller number from the larger; and for division, an inner check refuses to divide by 0.

Indentation matters in Python. Other languages group statements with braces { }; Python groups them by indentation: statements with the same indentation form one block. Wrong indentation is a syntax error, and the program will not run.

Keep one style throughout a program. The usual Python style is 4 spaces for each level of indentation (the book suggests a tab; either works, but do not mix them).

Indentation is part of Python's grammar.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.