Reading — step 1 of 8
Learn
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
Three pieces:
- The keyword
if. - A condition that evaluates to a boolean (
age >= 18). - A colon
:ending the line. - 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.
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
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 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
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:
Nested ifs work but get hard to read past 2-3 levels. Often you can flatten them with and:
The conditional expression (ternary)
For simple if/else assignments, Python has a one-line form:
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
ifline:if x > 0is aSyntaxError. It must beif x > 0:. - Mixing tabs and spaces: you'll get
IndentationError: unexpected indentorTabError. Stick to spaces. - Using
=instead of==in the condition:if x = 10:is aSyntaxError. It must be==. - Forgetting to handle a case: if the
elseis 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…