Python if, elif, and else Statements
Learn how Python if, elif, and else statements choose one branch from multiple alternatives, with menu, range, input validation, and troubleshooting examples.
A conditional statement runs code depending on whether a condition is true or false. Python uses if, elif, and else to choose between possible paths.
An if/else decision has two possible paths: the if path runs when its condition is true, and the else path runs otherwise. An if/elif/else chain can choose among three or more alternatives. Common uses include menus, category selection, input validation, and status messages.
In a conditional chain, each possible path is called a branch. A condition is an expression that produces a Boolean value: either True or False.
Python if, elif, and else Syntax
The general structure contains one initial if clause, zero or more elif clauses, and an optional final else clause:
if condition:
statements
elif another_condition:
statements
else:
statements
ifis the first conditional clause and is always checked first.elifmeans “else if.” It adds another condition to the same decision chain.elseis an optional fallback branch. It has no condition.- Every condition is followed by a colon,
:. - Statements belonging to a branch must be indented. Four spaces is the usual style.
elif is Python syntax for an additional branch; it is not a standalone condition statement. It must follow an if or another elif in the same chain.
A small example
temperature = 22
if temperature < 10:
print("It is cold.")
elif temperature < 25:
print("It is mild.")
else:
print("It is warm.")
The indented print() statements are the blocks controlled by their corresponding clauses. Related branches should remain at the same indentation level.
Clause Roles
Evaluation Order and Branch Selection
Python evaluates conditions from top to bottom. It executes the first branch whose condition is true. After that branch runs, Python skips every later elif and the else branch.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("Below C")
Here, score >= 90 is false, so Python checks score >= 80. That condition is true, so it prints B and does not check the remaining branches.
The else branch runs only when every preceding condition is false. It is useful as a fallback for unmatched cases.
Order overlapping conditions carefully
When conditions overlap, put the most specific or highest threshold first. Otherwise, a broad condition may capture a value before a later branch can examine it.
score = 95
# Correct: the higher threshold comes first.
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "Needs improvement"
print(grade)
If score >= 70 appeared first, a score of 95 would match that condition and incorrectly receive C.
Conditions and Comparison Operators
Each if or elif condition must evaluate to a Boolean value. Comparison operators create Boolean results by comparing values.
Use == to compare values. Use = to assign a value to a variable:
choice = 2 # Assignment
if choice == 2: # Comparison
print("Option 2 selected.")
Using = where a comparison is needed causes a syntax error. For a broader review of these operators, see Python comparison operators.
Interactive Numbered Menu
This example displays five vehicle choices, reads the user's selection, converts the text to an integer, and selects one response.
print("Choose a vehicle:")
print("1. Bicycle")
print("2. Bus")
print("3. Car")
print("4. Train")
print("5. Boat")
selection = int(input("Choose an option: "))
if selection == 1:
print("You selected a bicycle.")
elif selection == 2:
print("You selected a bus.")
elif selection == 3:
print("You selected a car.")
elif selection == 4:
print("You selected a train.")
elif selection == 5:
print("You selected a boat.")
else:
print("That is not a supported vehicle choice.")
input() always reads user input as text. int() converts suitable text such as "2" into the integer 2, allowing numeric comparisons.
Example output
Choose a vehicle:
1. Bicycle
2. Bus
3. Car
4. Train
5. Boat
Choose an option: 2
You selected a bus.
If the user enters 0 or 6, conversion succeeds, but no listed comparison is true. The else branch then displays the invalid-selection message.
Invalid Numeric and Non-numeric Input
There are two different invalid-input cases:
- An unlisted numeric choice, such as
0or6, reaches the conditional chain and is handled byelse. - Non-numeric text, such as
two, cannot be converted byint(). Python raisesValueErrorbefore it reaches the conditional chain.
Safe numeric conversion
Wrap the conversion in try/except when users may enter arbitrary text:
try:
selection = int(input("Choose an option: "))
except ValueError:
print("Enter a whole number.")
else:
if selection == 1:
print("You selected a bicycle.")
elif selection == 2:
print("You selected a bus.")
elif selection == 3:
print("You selected a car.")
elif selection == 4:
print("You selected a train.")
elif selection == 5:
print("You selected a boat.")
else:
print("That is not a supported vehicle choice.")
The except ValueError block handles text that is not a whole number. Valid integers continue to the menu decision. You can learn more about exception handling in Python try/except statements.
Choosing elif or Separate if Statements
Use an if/elif/else chain when the outcomes are mutually exclusive: only one response should run.
points = 75
if points >= 90:
print("Excellent")
elif points >= 60:
print("Passing")
else:
print("Try again")
Use separate if statements when more than one action may need to run. Separate statements continue evaluating after a previous condition is true.
temperature = 30
if temperature > 20:
print("Wear light clothing.")
if temperature > 25:
print("Drink extra water.")
Both messages can appear because these are two independent decisions. Replacing the second if with elif would make the branches mutually exclusive.
More Range-Checking Examples
Letter grade classification
score = 88
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
Temperature advice
temperature = 28
if temperature < 10:
print("It is cold.")
elif temperature < 20:
print("It is mild.")
elif temperature < 30:
print("It is warm.")
else:
print("It is hot.")
These ranges are ordered from lower to higher values. Once a temperature matches one range, later ranges are skipped.
Readability and Maintainability
- Use descriptive conditions and output messages that explain the result.
- Order overlapping conditions from the most specific or highest threshold to the broader cases.
- Keep every branch at the same indentation level within a chain.
- Use
elsewhen an unmatched case needs a clear fallback. - Keep the chain manageable. An excessively long
elifsequence may be clearer as a dictionary lookup, a function, amatchstatement, or another data-driven structure.
The foundational if/elif/else structure is still the right starting point for understanding conditional branching. See the Python if statement for a single condition and Python if/else statements for two-way decisions.
Running and Troubleshooting Your Code
Save a menu example in a file such as filename.py, then run it from a terminal with:
python filename.py
Common problems
- Using
=instead of==: assignment is being used where equality comparison is required. Writeif selection == 2:. IndentationErroror code outside the intended branch: branch statements are not consistently indented. Indent each statement in a branch, typically by four spaces.- A later
elifnever runs: an earlier condition is too broad or already matches the same values. Review top-to-bottom evaluation and reorder the conditions. elsedoes not handle text such astwo:int()fails before the chain is reached. Usetry/except ValueError, or compare text choices directly.- More than one response appears: separate
ifstatements were used even though only one outcome should be selected. Use anif/elif/elsechain. elsecauses a syntax error: check that it has a trailing colon, is aligned with itsifandelifclauses, and belongs to an existing conditional chain.
Key Points
ifstarts a conditional decision.elifadds one or more alternative conditions.elseis an optional, condition-free fallback.- Colons and indentation define the structure of each branch.
- Use
==for comparison and=for assignment. - Use a chain for mutually exclusive outcomes and separate
ifstatements when multiple actions may run. - Handle non-numeric input around
int()withtry/except ValueError.