Skip to main content
Python•Last Updated : 20 Oct 2026
~35 min read

Conditionals: if, elif and else

Making decisions in Python: if, else and elif chains, truthy and falsy values, combining conditions, nesting versus flat logic, and the conditional expression.

Running code only when a condition holds

So far every line of a program has run. Real programs choose: show an error only if the input is invalid, apply a discount only on Tuesdays. The if statement runs its indented block only when its condition is true.

The condition is any expression; Python evaluates it and checks whether the result is true. Comparisons (>=, ==, in, ...) produce True or False directly. The line ends with a colon, and the block below it is indented by four spaces. The first line that is not indented marks the end of the block.

PythonA single if
1balance = 120
2price = 75
3if balance >= price:
4 balance -= price
5 print("Purchased. Remaining balance:", balance)
6print("Done")
Output
Purchased. Remaining balance: 45
Done

Two paths: if and else

else adds the path to take when the condition is false. Exactly one of the two blocks runs, never both and never neither.

else has no condition of its own; it simply catches everything the if did not.

PythonEither one branch or the other
1number = 17
2if number % 2 == 0:
3 print(number, "is even")
4else:
5 print(number, "is odd")
Output
17 is odd

Many paths: elif chains

When there are more than two cases, chain them with elif ("else if"). Python tests the conditions from top to bottom and runs the block of the first one that is true; everything after it is skipped, even if it would also be true. A final else handles whatever is left.

Because the first match wins, order matters. Put the most specific or most restrictive case first. In the example, checking score >= 50 before score >= 90 would label every high score as a pass.

Each later condition can also rely on the earlier ones being false: in the elif score >= 75 branch you already know the score is below 90, so there is no need to write 75 <= score < 90.

Tip

Use one if/elif/else chain for mutually exclusive cases, and separate if statements for independent checks that may all apply.

PythonGrading with an elif chain
1score = 82
2if score >= 90:
3 grade = "Distinction"
4elif score >= 75:
5 grade = "Merit"
6elif score >= 50:
7 grade = "Pass"
8else:
9 grade = "Not yet"
10print(score, "->", grade)
Output
82 -> Merit

Tracing a decision

Step through this program and watch which lines run. The elif line is never evaluated: once the if condition is true, the rest of the chain is skipped.

Free shipping over 50

Step 1 of 5
1total = 72
2shipping = 10
3if total >= 50:
4 shipping = 0
5elif total >= 25:
6 shipping = 5
7final = total + shipping
SteptotalshippingfinalState Evolution
172——total is set to 72.

Truthy and falsy values

A condition does not have to be a boolean. Python decides whether any value counts as true, its truthiness. These values are falsy:

  • False and None
  • zero of any numeric type: 0, 0.0
  • empty collections: "", [], (), {}, set()

Everything else is truthy. That allows natural checks such as if name: (is the name non-empty?) or if not items: (is the list empty?).

Be careful when 0 is a legitimate value. If discount = 0 means "no discount", if discount: is fine; but if you are checking whether a value was provided at all, test if discount is not None: so that a real 0 is not mistaken for "missing".

PythonTruthiness in conditions
1name = ""
2if not name:
3 name = "Guest"
4print("Hello,", name)
5
6for value in [0, 7, "", "0", None, [], [0]]:
7 print(repr(value), "->", bool(value))
Output
Hello, Guest
0 -> False
7 -> True
'' -> False
'0' -> True
None -> False
[] -> False
[0] -> True

Combining conditions

Use and, or and not to build compound conditions, and parentheses when mixing them. Two more tools keep conditions short and readable:

  • Chained comparisons: if 13 <= age <= 19: instead of if age >= 13 and age <= 19:.
  • Membership with in: if day in ("Saturday", "Sunday"): instead of comparing against each value with or.

A classic bug is if day == "Saturday" or "Sunday":. Python reads it as (day == "Saturday") or "Sunday", and a non-empty string is truthy, so the condition is always true.

PythonCompound conditions
1age = 16
2day = "Sunday"
3has_permission = True
4
5if 13 <= age <= 19:
6 print("Teenager")
7if day in ("Saturday", "Sunday"):
8 print("Weekend")
9if age >= 18 or has_permission:
10 print("May join the trip")
11if not (age >= 18):
12 print("Needs a guardian's signature")
Output
Teenager
Weekend
May join the trip
Needs a guardian's signature

Nested conditions and flat logic

An if can contain another if. Nesting is natural when the second question only makes sense after the first is answered, for example checking a password only after finding the user.

Deep nesting, however, quickly becomes hard to read. Two techniques flatten it:

  1. Combine conditions with and when both must hold for a single action.
  2. Handle the exceptional cases first, so the main case is not buried. Inside functions (next lessons) this becomes the guard clause: check what is wrong, return early, and let the normal path continue unindented.
PythonNested versus combined
1logged_in = True
2is_admin = False
3
4# Nested: correct but grows to the right
5if logged_in:
6 if is_admin:
7 print("Show admin panel")
8 else:
9 print("Show dashboard")
10else:
11 print("Show login page")
12
13# Flat: one level, same behaviour
14if not logged_in:
15 print("Show login page")
16elif is_admin:
17 print("Show admin panel")
18else:
19 print("Show dashboard")
Output
Show dashboard
Show dashboard

The conditional expression

When a decision only picks between two values, the conditional expression fits it on one line:

value_if_true if condition else value_if_false

It is an expression, so it can appear anywhere a value can: in an assignment, an f-string or a function argument. Keep it for simple choices; anything that needs elif or several statements belongs in a normal if block.

PythonChoosing a value inline
1items = 1
2label = "item" if items == 1 else "items"
3print(f"You have {items} {label} in your cart.")
4
5temperature = -3
6print("Freezing" if temperature < 0 else "Above zero")
Output
You have 1 item in your cart.
Freezing

Check your understanding

Suggested Quiz
Question 1 of 4

With `x = 15`, what does this print: `if x > 10: print("A")`, then `elif x > 5: print("B")`, then `else: print("C")`?

Practice

Four decision problems, from a single rule with exceptions to validation and grading tables.

[Problem]

Leap Year Check

Reveal Solution & Analysis
Model Solution
[Problem]

Cinema Ticket Price

Reveal Solution & Analysis
Model Solution
[Problem]

Triangle Classifier

Reveal Solution & Analysis
Model Solution
[Problem]

Grade Calculator with Edge Cases

Reveal Solution & Analysis
Model Solution

Quick Syntax & Reference Sheet

Concept / RuleSyntax / Usage
if / elif / elseif a: ... elif b: ... else: ...
Range checkif 0 <= x < 10:
Membershipif day in ("Sat", "Sun"):
Empty checkif not items:
None checkif value is None:
Conditional expressionlabel = "adult" if age >= 18 else "minor"

Common Pitfalls & Developer Mistakes

✕ Mistake 1:

Using = instead of == in a condition

Why it happens: if x = 5: is a SyntaxError because = is assignment.

Correction: if x == 5:
✕ Mistake 2:

Wrong order in an elif chain

Why it happens: A broad condition placed first catches cases meant for later branches.

Correction: Order conditions from most specific (or highest threshold) to most general.
✕ Mistake 3:

Comparing against several values with or

Why it happens: x == 1 or 2 is always truthy.

Correction: x in (1, 2)
✕ Mistake 4:

Using truthiness when 0 is valid

Why it happens: if quantity: treats a real quantity of 0 like a missing value.

Correction: if quantity is not None:

Frequently Asked Questions

Does Python have a switch statement?

Python 3.10 added match/case for structural pattern matching. For simple value checks an if/elif chain or a dictionary lookup is usually clearer, and both work on every Python 3 version.

Is else required after if?

No. Add else only when something must happen in the false case.

Can I write an if on one line?

if x: print(x) is legal, but the conventional style puts the block on its own indented line. The conditional expression a if cond else b is the idiomatic one-line choice between two values.

Hands-On Practice Problems

Article Tags:#Python#Conditionals#if elif else#Boolean Logic#Truthiness
Was this lesson clear and helpful?

Discussion (0)

Sign in to ask questions and reply.
Loading discussion…
Discuss in community