Skip to content
PythonControl Flowbeginner18 min read

if, elif, and else

Learn how Python makes decisions using if, elif, and else, with clear examples, dry runs, and practical exercises.

In this lesson, you will learn

  • ✓Explain how if, elif, and else control the flow of a Python program.
  • ✓Write conditional statements using correct syntax and indentation.
  • ✓Trace conditions in execution order and predict which branch executes.
  • ✓Handle multiple conditions, boundary values, and mutually exclusive branches.
  • ✓Write and test small programs that make decisions based on input values.

1. Understanding Conditional Statements

A conditional statement allows a program to choose what to do based on whether a condition is true. Python evaluates the condition and uses its truth value to decide which statements to execute.

The if statement checks a condition. If that condition is true, Python executes the indented block belonging to it. If the condition is false, Python skips that block and continues to the next applicable branch.

A condition can be a comparison such as score >= 40, a logical expression such as age >= 18 and has_id, or another expression whose truthiness Python can evaluate.

The statements controlled by a condition form a block. In Python, indentation defines that block, so the statements belonging to it must be indented consistently.

Execute a block when a condition is true

Execute a block when a condition is true
python
temperature = 30
 
if temperature > 25:
print("It is warm.")
 
print("Program finished.")
Output
It is warm. Program finished.

Python assigns 30 to temperature. The condition temperature > 25 evaluates to True because 30 is greater than 25. Python executes the indented print() statement and displays It is warm. The final print() statement is outside the if block, so it executes regardless of whether the condition is true or false.

Note

An if statement does not require an else branch. If its condition is false and there is no applicable alternative branch, Python simply skips the block.

2. Using if and else

Use else when a program needs one outcome if a condition is true and a different outcome if it is false. The else keyword does not take a condition of its own.

In an if/else structure, exactly one of the two branches executes. If the if condition is true, Python executes the if block and skips the else block. Otherwise, it executes the else block.

Both branches must contain at least one statement. An empty block is not valid Python unless you use a statement such as pass as a placeholder.

Check whether a student passes

Check whether a student passes
python
mark = 35
 
if mark >= 40:
print("Pass")
else:
print("Try again")
Output
Try again

The variable mark contains 35. Python evaluates mark >= 40. The result is False. Because the if block is skipped, Python executes the else block and displays Try again.

Note

The colon at the end of if and else introduces a block. The statements belonging to that block must be indented on the following lines.

3. Using elif for Multiple Conditions

The elif keyword means else if. It lets you test another condition when the preceding if or elif conditions were false.

You can use multiple elif branches when a program needs to choose among several outcomes. Python checks the conditions from top to bottom and executes the block belonging to the first condition that evaluates to true.

Once a branch in an if/elif/else chain has been selected, Python skips the remaining branches in that chain. An optional else block runs only when every preceding condition is false.

The order of conditions matters. A broad condition placed too early may prevent a more specific condition from being reached.

Assign a grade based on a score

Assign a grade based on a score
python
score = 82
 
if score >= 90:
print("A")
elif score >= 75:
print("B")
elif score >= 60:
print("C")
else:
print("D")
Output
B

The first condition, score >= 90, is false because 82 is less than 90. Python checks score >= 75 next. This condition is true because 82 is at least 75. Python executes the corresponding block and displays B. The remaining elif and else branches are skipped, even though Python has not evaluated their conditions.

Caution

Only the first true branch executes in one if/elif/else chain. Python does not execute every branch whose condition might be true.

4. Condition Order and Boundary Values

A boundary value is a value at or near a limit in a condition. For example, if a passing score is 40, the values 39, 40, and 41 are useful tests.

Choose comparison operators carefully. The expression score >= 40 includes 40, while score > 40 excludes it. Similarly, <= includes the boundary and < excludes it.

Condition order can change a program's result. When conditions overlap, Python selects the first true condition in the chain. More specific or higher-priority cases should therefore be checked before broader cases when the requirements call for it.

Test the passing boundary

Test the passing boundary
python
mark = 40
 
if mark >= 40:
print("Pass")
else:
print("Try again")
Output
Pass

The mark is exactly 40. The >= operator includes equality, so 40 >= 40 evaluates to True. Python executes the if block and displays Pass.

Note

For a score-based grading chain, test values immediately below, exactly at, and immediately above every threshold. This helps reveal mistakes involving <, <=, >, and >=.

5. Indentation and Nested Conditions

Python uses indentation to determine which statements belong to a conditional block. Four spaces per indentation level is the standard convention.

Statements aligned at the same indentation level belong to the same block. A statement that is indented further belongs to a nested block or another construct that introduces a block.

A nested condition is an if statement inside another if or else block. It is useful when a second decision should be made only after an earlier requirement has been satisfied.

Indentation is part of Python syntax, not merely a formatting preference. Incorrect indentation can cause an IndentationError or make a statement belong to a different block than intended.

Make a second decision inside an if block

Make a second decision inside an if block
python
age = 22
has_id = True
 
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Too young")
Output
Entry allowed

The outer condition checks whether age is at least 18. It evaluates to True. Python enters the outer if block and checks the nested condition has_id. Since has_id is True, Python displays Entry allowed. The nested else and outer else blocks are skipped.

Caution

Keep indentation consistent. Do not align a statement with the if keyword when it is supposed to belong to that if block.

6. Truthiness and Common Conditional Patterns

An if condition can evaluate a Boolean expression, but it can also use a value directly. Python evaluates the truthiness of that value to decide whether the block should run.

For example, an empty string is falsy, while a non-empty string is truthy. This makes a condition such as if username: useful for checking whether a string is non-empty.

A condition such as if items: checks whether a collection is non-empty. It does not check whether every item inside the collection is valid.

Choose a condition that clearly expresses the requirement. For numerical comparisons, use explicit comparisons such as score >= 40 rather than relying on the truthiness of a number.

Check whether a name was provided

Check whether a name was provided
python
username = "Mira"
 
if username:
print("Name provided")
else:
print("Name missing")
Output
Name provided

The string stored in username is non-empty. Non-empty strings are truthy, so the if block executes. Python displays Name provided.

Note

The next lesson explores nested conditions in more detail. For now, focus on understanding which condition is evaluated and which block Python executes.

7. Practical Decision-Making Example

Conditional statements become easier to understand when they represent a clear requirement. Before writing code, identify the possible outcomes, define the conditions for each outcome, and arrange the conditions in the correct order.

The following example classifies a score into three categories. The first condition checks the highest category, the next checks the middle category, and else handles every remaining score.

The example assumes score is an integer between 0 and 100. If values come from external input, a real program should also validate that the value is numeric and within the allowed range.

Classify a score

Classify a score
python
score = 68
 
if score >= 80:
print("Distinction")
elif score >= 50:
print("Pass")
else:
print("Needs improvement")
Output
Pass

The score is 68. The first condition, score >= 80, is false. The second condition, score >= 50, is true. Python displays Pass and skips the else block.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Forgetting the colon after if, elif, or else.

Why it happens: Python uses a colon to mark the start of a conditional suite, so leaving it out causes a syntax error.

Incorrect Approach
script.py
python
Forgetting the colon after if, elif, or else.
Correct Solution
script.py
python
Write a colon at the end of each conditional header, such as if score >= 40:. A missing colon causes a SyntaxError.

Key takeaway: Write a colon at the end of each conditional header, such as if score >= 40:. A missing colon causes a SyntaxError.

#2 Indenting statements incorrectly.

Why it happens: Indentation defines which statements belong to each branch; inconsistent indentation can change program structure or raise an error.

Incorrect Approach
script.py
python
Indenting statements incorrectly.
Correct Solution
script.py
python
Indent each statement belonging to a block consistently, normally using four spaces per level. Check which block should contain each statement.

Key takeaway: Indent each statement belonging to a block consistently, normally using four spaces per level. Check which block should contain each statement.

#3 Using multiple independent if statements when only one branch should execute.

Why it happens: Separate if statements are evaluated independently, so more than one block may run; an if/elif/else chain selects at most one branch.

Incorrect Approach
script.py
python
Using multiple independent if statements when only one branch should execute.
Correct Solution
script.py
python
Use an if/elif/else chain for mutually exclusive outcomes. Separate if statements are evaluated independently and can execute more than one block.

Key takeaway: Use an if/elif/else chain for mutually exclusive outcomes. Separate if statements are evaluated independently and can execute more than one block.

#4 Placing a broad condition before a more specific condition.

Why it happens: An earlier broad condition can match first and prevent a later, more specific elif branch from running.

Incorrect Approach
script.py
python
Placing a broad condition before a more specific condition.
Correct Solution
script.py
python
Order overlapping conditions so the intended higher-priority case is checked first. For example, check score >= 90 before score >= 60 when assigning a separate excellent category.

Key takeaway: Order overlapping conditions so the intended higher-priority case is checked first. For example, check score >= 90 before score >= 60 when assigning a separate excellent category.

#5 Using else with a condition.

Why it happens: else is the fallback branch and does not take a condition; use elif when another condition is required.

Incorrect Approach
script.py
python
Using else with a condition.
Correct Solution
script.py
python
Use elif when another condition must be checked. The else keyword has no condition and handles the remaining cases.

Key takeaway: Use elif when another condition must be checked. The else keyword has no condition and handles the remaining cases.

#6 Ignoring values exactly on a threshold.

Why it happens: Threshold checks can fail at exact boundary values if comparisons use the wrong combination of <, <=, >, or >=.

Incorrect Approach
script.py
python
Ignoring values exactly on a threshold.
Correct Solution
script.py
python
Decide whether the boundary is included and choose the operator accordingly. Test values immediately below, at, and above the threshold.

Key takeaway: Decide whether the boundary is included and choose the operator accordingly. Test values immediately below, at, and above the threshold.

#7 Assuming an if statement only accepts expressions that explicitly return True or False.

Why it happens: An if condition can use any expression whose result is evaluated for truthiness, not only expressions that explicitly return a Boolean.

Incorrect Approach
script.py
python
Assuming an if statement only accepts expressions that explicitly return True or False.
Correct Solution
script.py
python
Python also evaluates truthiness. For example, an empty list is falsy and a non-empty list is truthy.

Key takeaway: Python also evaluates truthiness. For example, an empty list is falsy and a non-empty list is truthy.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What are if, elif, and else in Python?
Answer:
They are keywords used for conditional branching. if checks the first condition, elif checks another condition when preceding conditions in the chain were false, and else handles the remaining case when it is present.
Q2:Can an if statement have multiple elif branches?
Answer:
Yes. A conditional chain can contain multiple elif branches. Python checks them in order and executes the first branch whose condition is true. The else branch is optional.
Q3:What happens when multiple conditions in an if/elif/else chain are true?
Answer:
Only the first true branch executes. After selecting that branch, Python skips the remaining branches in the same chain.
Q4:What is the difference between elif and a separate if statement?
Answer:
An elif belongs to the same conditional chain, so it is checked only when preceding branches in that chain have not been selected. A separate if statement is evaluated independently and may execute even if an earlier if block executed.
Q5:Why is indentation important in Python?
Answer:
Indentation defines which statements belong to a block. Conditional statements require their controlled statements to be indented. Incorrect indentation can cause an IndentationError or produce a different block structure than intended.
Q6:How can condition order cause a bug?
Answer:
If a broad condition is checked before a more specific condition, the broad condition may match first and prevent the specific branch from running. For example, score >= 60 should come after score >= 90 when those thresholds represent different categories.
Q7:How would you test a conditional statement?
Answer:
Test ordinary values, values at each threshold, and values immediately above and below the thresholds. Trace each condition in order and compare the actual output with the expected result.
Q8:Can a Python if statement use a string or list directly as its condition?
Answer:
Yes. Python evaluates truthiness in a Boolean context. A non-empty string or list is truthy, while an empty string or list is falsy. This is useful for checking whether a value or collection is present.

Key takeaways

  • Use if to execute a block when a condition is truthy.
  • Use else for the remaining case and elif to check additional conditions.
  • Only one branch executes in a single if/elif/else chain.
  • Python uses indentation to define conditional blocks, and conditional headers end with a colon.
  • Condition order matters when conditions overlap; check higher-priority or more specific cases first.
  • Test boundary values to catch mistakes involving comparison operators.
  • Python conditions can use truthy and falsy values, not only explicit Boolean expressions.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: