Skip to content
If, Elif, Else
step 1/8

Reading — step 1 of 8

Learn

~3 min readMaking Decisions

You've learned how to ask yes-or-no questions with comparisons and boolean logic. Now it's time to do something with the answers. The if statement is how your program chooses between paths based on a condition. It's arguably the most important concept in programming.

The simplest form

python

Three pieces:

  1. The keyword if.
  2. A condition that evaluates to a boolean (age >= 18).
  3. A colon : ending the line.
  4. An indented block below — the code that runs when the condition is True.

If the condition is False, the indented block is skipped entirely. That's it.

Indentation IS the syntax

In most languages, code blocks are wrapped in { ... } or begin ... end. Python uses indentation instead. Whitespace isn't decorative — it's how Python knows what's inside the if block and what isn't.

python

The Python community uses 4 spaces per indent level. Tabs work but mixing tabs with spaces is a recipe for IndentationError. Pick spaces and stick with them — most editors are configured for this by default.

else — the fallback path

python

else runs ONLY when the if condition was False. Exactly one of the two blocks will run — never both, never neither.

elif — multiple paths

When there are MORE than two outcomes, chain conditions with elif ("else if"):

python

Python checks each condition in order. The FIRST one that's True runs, and the rest are skipped. So a score of 95 prints A only — the other branches don't even get checked.

You can have as many elif branches as you need. The final else is optional but useful for catching every case you didn't list.

Order matters

python

Check the most specific or strictest condition FIRST. With if/elif, only the first matching branch runs.

Nested ifs

You can put an if inside another:

python

Nested ifs work but get hard to read past 2-3 levels. Often you can flatten them with and:

python

The conditional expression (ternary)

For simple if/else assignments, Python has a one-line form:

python

Reads as: "adult if age >= 18, else minor." Useful when you'd otherwise need 4 lines for what's really one decision.

Common mistakes

  • Forgetting the colon at the end of the if line: if x > 0 is a SyntaxError. It must be if x > 0:.
  • Mixing tabs and spaces: you'll get IndentationError: unexpected indent or TabError. Stick to spaces.
  • Using = instead of == in the condition: if x = 10: is a SyntaxError. It must be ==.
  • Forgetting to handle a case: if the else is missing and no condition matches, NOTHING runs — silent bug.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

If, Elif, Else — Python Fundamentals