Conditional Statements (if, elif, else)
Learn how to control the flow of a Python program using if, elif, and else statements, along with the conditional expression.
Introduction
Every real program needs to make decisions: show a discount if a cart total is high enough, display an error if a password is too short, or greet a user differently depending on the time of day. Conditional statements are how Python makes these decisions.
Python uses the keywords if, elif (short for "else if"), and else to run different blocks of code depending on whether a condition is True or False.
- How to write if, if...else, and if...elif...else statements.
- How to nest conditionals inside one another.
- How to combine multiple conditions using logical operators.
- How to write a compact conditional expression (ternary).
- Common indentation and comparison mistakes to avoid.
The if Statement
An if statement runs a block of code only when its condition evaluates to True. The block must be indented, and the line ends with a colon.
age = 20
if age >= 18:
print("You are eligible to vote.")You are eligible to vote.If the condition were False, the indented block would simply be skipped, and the program would continue with whatever code comes after it.
if...else
An else block runs whenever the if condition is False, giving you a fallback path.
age = 15
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")You are not eligible to vote yet.if...elif...else
When you have more than two possible outcomes, use one or more elif blocks between if and else. Python checks each condition top to bottom and runs only the first one that is True.
marks = 72
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
print("Grade:", grade)Grade: CEven if multiple elif conditions would technically be True, Python stops checking as soon as it finds the first True condition and runs only that block.
Nested Conditionals
You can place an if statement inside another if or else block. This is called nesting, and it is useful when a decision depends on another decision that came before it.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed.")
else:
print("ID required for entry.")
else:
print("You must be 18 or older.")Entry allowed.Deeply nested if statements (4+ levels) become hard to read. Often, combining conditions with "and" or restructuring with elif is clearer than heavy nesting.
Combining Conditions with Logical Operators
Instead of nesting, you can often combine multiple conditions into a single if statement using the logical operators and, or, and not.
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed.")
else:
print("Entry denied.")
temperature = 5
if temperature < 0 or temperature > 40:
print("Extreme weather warning.")
else:
print("Weather is normal.")Entry allowed.
Weather is normal.| Operator | Meaning | Example |
|---|---|---|
| and | True only if both conditions are True | age >= 18 and has_id |
| or | True if at least one condition is True | temperature < 0 or temperature > 40 |
| not | Reverses True to False and vice versa | not has_id |
The Conditional Expression (Ternary)
Python offers a compact one-line way to choose between two values based on a condition: value_if_true if condition else value_if_false. This is often called a ternary expression.
age = 16
status = "Adult" if age >= 18 else "Minor"
print(status)
# Equivalent long form:
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(status)Minor
MinorUse the conditional expression for short, simple choices, especially when assigning a variable. For anything with multiple branches or side effects, a full if/elif/else block is more readable.
Common Mistakes
- Using = (assignment) instead of == (comparison) inside a condition — Python actually raises a SyntaxError for this in an if statement, which helps catch it early.
- Forgetting the colon (:) at the end of an if, elif, or else line.
- Inconsistent indentation, which causes an IndentationError or unexpected logic.
- Writing "if x == True:" instead of simply "if x:" — the extra comparison is redundant.
- Chaining unnecessary elif branches when the conditions are mutually exclusive and could be simplified.
age = 20
# Correct comparison
if age == 18:
print("Exactly 18")
else:
print("Not exactly 18")Not exactly 18Best Practices
- Keep conditions simple and readable; break complex logic into named variables.
- Use elif instead of multiple separate if statements when only one branch should run.
- Avoid deeply nested conditionals — flatten logic with and/or where possible.
- Use the ternary expression only for short, simple value choices.
- Always double-check == vs = when writing comparisons.
Frequently Asked Questions
Can I use elif without an else?
Yes. else is optional — you can have an if with one or more elif blocks and no else at all if there is no fallback case needed.
Can I have multiple elif blocks?
Yes, you can chain as many elif blocks as needed between if and else.
What counts as "falsy" in an if condition?
Values like 0, 0.0, "", None, empty lists [], and empty dictionaries {} are treated as False; almost everything else is treated as True.
Is the ternary expression slower than a full if/else?
No, performance is essentially identical — the ternary form is purely a shorter way to write the same logic.
Why did Python raise a SyntaxError when I used = in an if statement?
Python intentionally disallows assignment (=) inside a condition to prevent the classic bug of confusing it with comparison (==).
Key Takeaways
- if runs code when a condition is True; else provides a fallback.
- elif lets you check multiple conditions in sequence, running only the first True branch.
- Conditionals can be nested, but combining conditions with and/or is often clearer.
- The ternary expression (x if condition else y) is a compact way to choose between two values.
- Common mistakes include mixing up = and ==, missing colons, and inconsistent indentation.
Summary
Conditional statements let your programs make decisions and respond differently to different situations. With if, elif, else, and the ternary expression, you can express almost any decision-making logic clearly and concisely.
Next, you will learn about the match-case statement, Python's modern alternative for handling many possible values cleanly.
- You can write if, elif, and else statements confidently.
- You understand nested conditionals and when to avoid them.
- You can combine conditions using and, or, and not.
- You are ready to learn the match-case statement.