Make Decisions with if, elif and else
So far a Python program runs every line, from top to bottom, every time. Real programs have to react: say "Correct" to a right answer and something else to a wrong one. This page shows how a program chooses which lines to run with if, elif and else, how Python knows which lines belong to each choice, and how to join several conditions into one.
Running a block only when a condition is True
A comparison such as answer == "paris" gives back True or False. An if statement uses that result to decide whether some lines run at all. It is written as the word if, then a condition (an expression that gives True or False, most often a comparison), then a colon. The lines under it, pushed to the right, form its block: they run only when the condition is True.
Often you also want something to happen in every other case. That is what else is for. It has no condition of its own: it simply catches everything the if did not.
answer = input("Capital of France? ").strip().lower()
if answer == "paris":
print("Correct!")
else:
print("Not quite. It is Paris.")
print("Next question.")Python reads the condition first. If the person typed Paris, the tidied answer is "paris", the comparison is True, and Python runs the if block and skips the else block. If they typed anything else, it skips the if block and runs the else block. Exactly one of the two runs, never both and never neither. After that, the program goes on with the next line that is not part of the statement, so Next question. is printed in both cases.
- answer == "paris" condition
- print("Correct!") if block
- print("Not quite...") else block
- print("Next question.") the program goes on
- answer == "paris" to print("Correct!"): True
- answer == "paris" to print("Not quite..."): False
- print("Correct!") to print("Next question.")
- print("Not quite...") to print("Next question.")
The else part is optional. Without it, an if whose condition is False does nothing at all, and the program moves straight on.
True or false?
An else block runs after the if block, as an extra step, when the condition is True.
False. The if block and the else block exclude each other: when the condition is True only the if block runs, and when it is False only the else block runs.
An if statement without an else may run none of its lines.
True. When the condition is False and there is no else, Python skips the block and continues with the next line after the statement.
Indentation decides which lines belong to a branch
Each choice in an if statement is called a branch. Python needs to know where a branch's block starts and where it ends, and it reads that from the indentation: the spaces at the start of a line. A line that ends with a colon opens a block. The lines after it that are indented further belong to that block. The first line that steps back to the level of the if ends the block and is no longer part of the branch.
temperature = 30
if temperature > 25:
print("It is hot today.")
print("Drink some water.")
print("Have a nice day.")With temperature = 30 all three lines are printed. With temperature = 18 only Have a nice day. is printed, because the two indented lines belong to the block and the block is skipped. Moving that last line four spaces to the right would change what the program does: it would join the block and be printed only on hot days. In Python, indentation is not decoration; it is part of the meaning.
The usual style is four spaces for each level, and every line of one block must be indented by the same amount. Code editors made for Python insert the four spaces for you when you press Enter after a colon. Use spaces only: a mix of tabs and spaces can stop the file from running.
True or false?
Moving a line from four spaces of indentation back to none can change which lines run.
True. At four spaces the line belongs to the if block and runs only when the condition is True; at the left edge it is after the statement and runs every time.
When the indentation does not make sense, Python refuses to run the file at all, the same way it refuses a file with a syntax error. In fact, an IndentationError is a kind of syntax error, and its message names the file and the line where Python noticed the problem. These are the mistakes beginners make most:
# 1. Nothing indented after the colon
if temperature > 25:
print("It is hot today.")
# 2. A line indented deeper for no reason
if temperature > 25:
print("It is hot today.")
print("Drink some water.")
# 3. Stepping back to a level no line used before
if temperature > 25:
print("It is hot today.")
print("Drink some water.")| The mistake | The last line of the message |
|---|---|
| A block that is not indented (1) | IndentationError: expected an indented block after 'if' statement on line 2 |
| A line indented deeper than its block (2) | IndentationError: unexpected indent |
| A step back to an unused level (3) | IndentationError: unindent does not match any outer indentation level |
| Tabs and spaces mixed | TabError: inconsistent use of tabs and spaces in indentation |
| The colon missing after the condition | SyntaxError: expected ':' |
In the first case the message points at the line that is not indented and names the line of the if it should belong to. In the third case the line that steps back has four spaces, but the only levels used before are no spaces (the if) and eight spaces (the block), so Python cannot tell which block it means. A line that steps back must land exactly on a level an earlier line used.
More than two cases with elif
An if with an else chooses between two cases. For a third and a fourth case, put one or more elif parts between them. The word is short for "else if": each elif has its own condition, which is only looked at when every condition above it was False.
score = int(input("Your score (0-100): "))
if score >= 90:
print("Excellent")
elif score >= 70:
print("Good")
elif score >= 50:
print("Pass")
else:
print("Try again")Python checks the conditions from the top, one after another. The first one that is True wins: its block runs, and the rest of the statement is skipped, including the conditions below it, which are not even checked. Only when every condition is False does the else block run. However many parts the chain has, at most one block runs.
- if score >= 90 True: prints Excellent, the chain stops
- elif score >= 70 True: prints Good, the chain stops
- elif score >= 50 True: prints Pass, the chain stops
- else every condition was False: prints Try again
- if score >= 90 to elif score >= 70: False
- elif score >= 70 to elif score >= 50: False
- elif score >= 50 to else: False
To predict which branch runs, walk down the chain with the value and stop at the first condition that holds:
| score | Conditions checked | Printed |
|---|---|---|
| 95 | score >= 90 is True | Excellent |
| 70 | score >= 90 False, score >= 70 True | Good |
| 64 | False, False, score >= 50 True | Pass |
| 12 | False, False, False | Try again |
A score of 95 also makes score >= 70 and score >= 50 true, yet only Excellent is printed. That is why the order of the parts matters. If the chain started with if score >= 50:, a score of 95 would stop there and print Pass, and the Excellent and Good branches could never run. When the conditions overlap like this, put the strictest one first.
The parts always come in the same order: one if first, any number of elif parts after it, and at most one else, last. The if, every elif and the else sit at the same indentation, each ending with a colon. An elif placed after the else is a syntax error.
True or false?
In an if/elif chain, every block whose condition is True runs, from top to bottom.
False. Only the first True condition wins. Its block runs and the rest of the chain is skipped without checking the remaining conditions.
With the chain above, a score of exactly 90 prints Excellent.
True. 90 >= 90 is True, because >= means greater than or equal, so the very first condition holds.
An else can carry its own condition, such as else score < 50.
False. else never has a condition: it catches every case the conditions above it did not. A case with its own condition is an elif.
Joining and reversing conditions with and, or, not
Sometimes one comparison is not enough to decide. A cinema lets you in when you are old enough and you have a ticket; a quiz accepts an answer when it is "yes" or "y". Python has three words for this, and each one works on conditions that are already True or False:
A and BisTrueonly when bothAandBareTrue.A or BisTruewhen at least one of them isTrue.not Areverses one condition:TruebecomesFalseandFalsebecomesTrue.
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
age = 15
has_ticket = True
if age >= 12 and has_ticket:
print("Enjoy the film.")
answer = input("Continue? ").strip().lower()
if answer == "yes" or answer == "y":
print("Let's go on.")
if not answer == "":
print("You typed something.")Python works out the comparisons first and then joins their results. In the first if, age >= 12 is True and has_ticket is True, so the whole condition is True. With age = 10 the first half would be False, and then and already knows the answer: Python does not even look at the second half. In the same way, or stops at the first half when it is True.
When one condition uses more than one of these words, not is applied first, then and, then or. So not answer == "" means not (answer == ""), the opposite of "the answer is empty". When a condition mixes and with or, write parentheses around the part that belongs together, such as (day == "sat" or day == "sun") and not raining: it is easier to read and you do not have to remember the order.
A mistake almost everyone makes once is writing answer == "yes" or "y" as a shortcut. Python reads it as (answer == "yes") or "y". When the answer is not "yes", the left side is False, and the result of the whole or is the string "y" itself. In a condition, a string that is not empty counts as true. So the branch runs for every answer, even "no". Each side of or needs its own full comparison: answer == "yes" or answer == "y".
True or false?
if answer == "yes" or "y": runs its block only when the answer is yes or y.
False. It is read as (answer == "yes") or "y". For any other answer it gives the non-empty string "y", which counts as true, so the block runs every time.
With age = 10 and has_ticket = True, the condition age >= 12 and has_ticket is False.
True. age >= 12 is False, and and needs both sides to be True, so the whole condition is False and the block is skipped.
not answer == "" is True when the person typed at least one character.
True. It means not (answer == ""). For a non-empty answer the comparison is False, and not turns it into True.