Skip to main content

The Else Keyword

Whatever the earlier conditions did not catch ends up in the else block.

Python runs it only after the if condition, and any elif conditions, have all turned out False.

Example

Prompt
Write a Python program that uses if, elif, and else to compare two variables and print which is greater or if they are equal.
Output: complete Python program

Else Without Elif

An else does not need an elif before it.

That gives you a plain choice between two paths. When the condition holds, the first block runs; when it doesn't, the else block runs instead.

Example

Prompt
Write a Python program that uses if and else (without elif) to check if b is greater than a.
Output: complete Python program

How Else Works

Think of else as the default action, a "catch-all" for every case that your if and elif statements left uncovered. It runs when all the conditions before it were false.

Note: Nothing can follow an else in the chain, so it always comes last and no elif may appear after it.

Example

Telling even numbers from odd ones:
Prompt
Write a Python program that checks whether a number is even or odd using if and else.
Output: complete Python program

Complete If-Elif-Else Chain

Together, if, elif and else give you a complete decision-making structure.

Example

Sorting temperatures into categories:
Prompt
Write a Python program that classifies a temperature value using if, elif, and else into hot, warm, cool, or cold.
Output: complete Python program

Else as Fallback

Because else takes over when no earlier condition was true, it makes a good safety net. That is handy for handling errors, validating data and supplying default values.

Example

Checking a username before using it:
Prompt
Write a Python program that validates a username and prints a welcome message or an error using if and else.
Output: complete Python program