LESSON · 1 OF 6

if, elif, and else

if, elif, and else

An if statement runs a block of code only when a condition is true. Add elif to test more conditions, and else to catch everything left over. This is how a script makes a decision instead of doing the same thing every time.

The basic if

python
cpu = 92
if cpu > 90:
    print("CPU is critical")

The expression after if evaluates to true or false. When it's true, the indented block runs. When it's false, Python skips the block and carries on.

Indentation defines the block

Python has no curly braces. The indented lines under an if are its block, and four spaces is the standard indent. Every line at that indent belongs to the block. The first line that dedents ends it.

python
if cpu > 90:
    print("critical")
    print("paging on-call")
print("done")   # not indented, so it always runs

elif and else

Chain more tests with elif, and give a fallback with else:

python
if cpu > 90:
    print("critical")
elif cpu > 70:
    print("warning")
else:
    print("ok")

Python checks the conditions top to bottom, runs the first block whose condition is true, and skips the rest. else runs only when none of the conditions matched.

Only one branch runs, so order matters

An if/elif/else chain runs at most one block. Put the tightest condition first. If you tested cpu > 70 before cpu > 90, a value of 95 would match the warning branch and never reach critical.

Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute