If / Elif / Else
Statements in Python
Learn to write conditional logic that lets your programs make decisions based on Boolean expressions and proper indentation.
What Are Conditional Statements?
Every meaningful program needs to make decisions. Conditional statements let Python choose which block of code to run based on whether a condition is True or False.
Boolean Expressions: The Foundation
Every condition evaluates to a Boolean value: either True or False. Python provides comparison and logical operators to build these expressions.
== != < > <= >=and or notin not inAnatomy of an if Statement
The Full if / elif / else Chain
Decision Flow: How Python Evaluates
Key Distinction: Chained vs. Separate
Why Indentation Matters
Unlike most languages, Python uses indentation (whitespace) to define code blocks. Incorrect indentation causes IndentationError or, worse, silent logic bugs.
Step-by-Step: Writing Conditionals
age >= 18.if, add elif for extra cases, end with else as a catch-all.Example 1: Even or Odd
Example 2: Temperature Advice
Example 3: Nested Conditionals
Combining Conditions with Logical Operators
Common Mistakes to Avoid
if x > 5 without : at the end causes a SyntaxError. Every if, elif, and else line must end with a colon.= (assignment) instead of == (comparison) in a condition. Python will raise a SyntaxError inside an if.Quick Reference Table
| Keyword | Purpose | Condition? | Required? |
|---|---|---|---|
if |
First check in a chain | Yes | Yes (always) |
elif |
Additional check(s) | Yes | No (0 or more) |
else |
Catch-all fallback | No | No (0 or 1) |
Question 1 of 5
What will the following code print?x = 15if x > 20: print("A")elif x > 10: print("B")elif x > 5: print("C")else: print("D")
15 > 20 is False, but 15 > 10 is True, so "B" prints. Because this is an if/elif chain, the remaining branches are skipped even though 15 > 5 is also True.Question 2 of 5
Which line will cause a SyntaxError?
x = 10 uses the assignment operator instead of the comparison operator ==. Python does not allow assignment inside an if condition, so it raises a SyntaxError.Question 3 of 5
How many spaces does PEP 8 recommend for each indentation level in Python?
Question 4 of 5
What is printed when this code runs?val = 50if val > 40: print("X")if val > 30: print("Y")if val > 20: print("Z")
Question 5 of 5
What keyword completes this code so it prints "child" when age is under 13?if age >= 18: print("adult")____ age >= 13: print("teen")____: print("child")
elif (an additional condition check) and the third needs else (the catch-all with no condition). Using elif and else creates a proper chain where exactly one block runs.