Python · Beginner
Conditions: if, elif and else in Python
In short: An if statement runs its indented block only when its condition is true; elif adds further conditions tested in order, and else runs when none matched. Python runs the first block whose condition holds and skips the rest of the chain, so branch order matters.
Choosing a path
Real programs need to react: charge one price below a weight limit and another above it, reject an empty name, stop when stock is gone. The if statement makes a block conditional: Python evaluates the expression after if, runs the indented block when it is true, and otherwise skips it and continues after it.
else attaches an alternative block that runs only when the if condition was false. elif ("else if") tests a second condition when the first failed, then a third, and so on. The whole chain is one statement: Python tests the conditions from the top, runs the block of the first true one, and ignores every later branch even if its condition would also have held. That is why ordering matters, and why a chain differs from a series of independent if statements, each of which is tested regardless of the others.
The condition does not have to be a comparison. Python accepts any value and asks whether it is truthy. Numbers are truthy unless they are zero; strings, lists and other collections are truthy unless they are empty; None is falsy. So if items: reads as "if there are any items", and if not name: as "if the name is missing or empty". Comparisons, and, or and not from the operators lesson build richer conditions, and in checks membership: if choice in ("y", "yes"):.
Blocks can nest: an if inside another if's block is indented one level further. Two levels are fine; at four it is usually clearer to combine conditions with and or move part of the logic into a function.
Syntax
if condition:
block # runs when condition is truthy
elif other_condition:
block # tested only if the first was false
else:
block # runs when nothing above matched
label = "even" if n % 2 == 0 else "odd" # conditional expressionAny number of elif branches may follow an if; else is optional and must come last. The one-line conditional expression picks one of two values and belongs inside larger expressions; it does not run blocks.
A price with three tiers
Parcel postage depends on weight. The program is run with the input 2.4.
weight = float(input())
if weight <= 1:
cost = 4
elif weight <= 5:
cost = 7
else:
cost = 12
print("Weight:", weight, "kg")
print("Cost:", cost)Input given to the program: 2.4
Output
Weight: 2.4 kg Cost: 7
2.4 fails the first test and passes the second, so cost becomes 7 and the else branch is skipped. Because the chain stops at the first true condition, the second branch need not say 1 < weight <= 5; passing the first test already rules out the light parcels. Swap the two tests and every parcel up to 5 kg would cost 7, because weight <= 5 would catch the light ones first.
Truthiness in conditions
None of these conditions contains a comparison operator.
unread = []
name = ""
retries = 3
note = None
if unread:
print("You have messages")
else:
print("No new messages")
if not name:
print("Name is required")
if retries:
print("Retries left:", retries)
if note is None:
print("No note attached")Output
No new messages Name is required Retries left: 3 No note attached
The empty list and the empty string count as false, the non-zero integer as true. is None tests for None specifically, which matters when 0 or an empty string would be a legitimate value that must not be treated as "nothing".
Combining and nesting conditions
A library loan check. The program is run with the input lines member and 3.
status = input()
books_out = int(input())
if status == "member" and books_out < 5:
print("Loan approved")
if books_out == 4:
print("This is your last slot")
elif status == "member":
print("Limit reached: return a book first")
else:
print("Membership required")
kind = "heavy reader" if books_out >= 3 else "casual reader"
print(kind)Input given to the program: member ↵ 3
Output
Loan approved heavy reader
The first branch checks two things at once with and. The nested if runs only inside that branch, and here it is false (3 is not 4), so nothing extra prints. The elif does not repeat the books_out check: reaching it already means the member has five or more books out. The last line is a conditional expression that evaluates to one of two strings.
Common mistakes
Ordering the branches from widest to narrowest
Why it goes wrong: With
if x <= 100:beforeelif x <= 10:, the second branch can never run: every value that satisfies it also satisfied the first. Python does not warn about unreachable branches.Fix: Order the tests so that each is narrower than the ones below it, or make each condition self-contained with both bounds.
Python · fixif score >= 90: grade = "A" elif score >= 75: grade = "B" else: grade = "C"Comparing to True or False explicitly
Why it goes wrong:
if done == True:works but is redundant, andif flag == "True":compares to a string and never matches a bool. The condition already is a truth value.Fix: Write
if done:andif not done:.Using = inside a condition
Why it goes wrong:
if count = 0:is a SyntaxError because=assigns. Python refuses it precisely to catch this slip.Fix: Compare with
==. To assign and test in one go, the walrus operator:=(Python 3.8 and later) exists:if (n := len(items)) > 10:.Independent ifs where a chain was meant
Why it goes wrong: Two separate if statements both run their tests, so one value can trigger both blocks. With
if x > 0:followed byif x > 10:, the number 15 prints from both.Fix: Use
elifwhen the branches are alternatives and exactly one should run.
What counts as false
| Value | In a condition |
|---|---|
| 0 and 0.0 | false |
| "" (empty string) | false |
| [], (), {} (empty collections) | false |
| None | false |
| any other number, including -1 | true |
| any non-empty string, including "0" and "False" | true |
| any non-empty collection | true |
Where you use this
Validating input is the first place conditions earn their keep. A sign-up form should refuse an empty username, reject an age outside a sensible range, and only then create the account. Written as a chain, each check reports one clear problem and stops, so the user sees the first thing to fix. The same shape appears in pricing rules, in access control (if role == "admin" or owner == user:), and inside loops that decide whether to skip an item or stop, which the loops lesson covers next.
name = input().strip()
age = int(input())
if not name:
print("Name is required")
elif age < 13:
print("Too young to register")
else:
print("Account created for", name)Key points
ifruns a block when its condition is truthy;elsecovers the other case.- An
if/elif/elsechain runs exactly one block: the first whose condition is true. - Order branches from most specific to least specific.
- Empty collections, empty strings, 0 and None are false; nearly everything else is true.
- Test for None with
is None, not== None. x if cond else yis an expression that picks a value; it does not replace blocks.
Try it yourself
The program labels a temperature as Cold or Hot. Add an elif so that temperatures from 10 up to and including 24 print Mild, with Cold below 10 and Hot from 25 upward.
temp = int(input())
if temp < 10:
print("Cold")
else:
print("Hot")
18Mildtemp = int(input())
if temp < 10:
print("Cold")
elif temp <= 24:
print("Mild")
else:
print("Hot")
Practise this
Related lessons
- Operators in PythonPython's arithmetic, comparison, logical, assignment and membership operators, with the precedence rules and the difference between /, // and %.8 min
- Loops in Python: for and whileHow a for loop walks through a sequence and a while loop repeats until a condition fails, with range(), enumerate(), break and continue explained by example.9 min
- Data Types in PythonThe core Python data types int, float, str, bool and None: how to check a type with type() and convert between types with int(), float() and str().8 min
Frequently asked questions
What is the difference between elif and writing another if?
elif belongs to the preceding if and is tested only when every earlier condition was false; once one branch runs, the rest of the chain is skipped. A second if is an independent statement that is always tested, so both blocks can run for the same value. Use elif for mutually exclusive alternatives and separate ifs for independent checks.
Does Python have a switch statement?
Not a switch keyword. Since Python 3.10 there is match, which compares a value against a series of case patterns and can take apart tuples and dictionaries as it goes. For matching one variable against a handful of constants, an if/elif chain or a dictionary lookup is still the simplest option and is what most code uses.
Can I write an if statement on one line?
You can put a single statement after the colon, as in if x > 0: print(x), but style guides discourage it because it hides the block. The idiomatic one-line form is the conditional expression value_if_true if condition else value_if_false, which chooses between two values rather than running statements.
How this page was checked. Every program on it was run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.