Python: Conditional Statements (if, elif, else) with Examples

Every useful program makes choices. A login form letting you in or turning you away, a game deciding you just lost, a thermostat kicking on at 18 degrees: in code, those choices run through the Python if else statement. This post covers if, elif, and else with tested examples, plus the truthy and falsy rules that quietly decide more than you expect.

“Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts.”

Fred Brooks, Mythical Man-Month

Last Updated: July 2026 | Tested on: Python 3.14.6 | Difficulty: Beginner | Reading Time: 15 minutes

Up to now, every line of your Python code ran top to bottom, every single time. Real programs don’t behave like that. A login page checks your password before it lets you in. A game checks if you’re still alive before drawing the next frame. A weather app gives you different advice for rain than it does for sunshine. The Python if else statement is how your code makes those decisions, and it is the focus of this post.

Think of a bouncer at a club. He looks at one thing, your ID, and picks one of two doors: “come in” or “not tonight.” An if statement is that bouncer. It looks at a condition, decides if it is True or False, and runs one block of code or another. Add an elif and now the bouncer has a guest list with several tiers. Add an else and you have the catch-all door for everyone who did not match anything above.

Python keeps this refreshingly clean compared to other languages. No curly braces. No parentheses required around the condition. Just a colon and some indentation. The structure reads almost like plain English, which is either elegant or terrifying depending on whether you got the indentation right.

The Simple if

TrueFalseTrueFalseTrueFalseStartif condition_1True or False?elif condition_2True or False?elif condition_3True or False?else blockruns when ALLconditions are Falseif block executescode indented under ifelif block 1 executescode indented under elifelif block 2 executescode indented under elifContinue afterif/elif/else💡 Key: Only ONE block runs.Python checks top-to-bottomand stops at the first True.Python if-elif-else: How Only One Branch Runs Top to Bottom

Tip: click the diagram to open it full screen, then use the zoom and pan controls for a closer look.

The flowchart traces how Python walks an if/elif/else chain from top to bottom. It checks each condition in order and runs only the first branch that comes back True. Here is the rule that surprises beginners: even if several conditions would be true, Python stops at the very first match and skips everything below it. That top-down, first-match behaviour is exactly why the order of your conditions matters so much, something the grading example below makes painfully clear.

If it helps, picture the metal detector at an airport: everyone walks through it, but the alarm only goes off for the person who triggers it. A simple if is exactly that, code that runs only when the condition fires and stays silent otherwise.

📄 simple_if.py: the smallest possible conditional

age = 28
if age >= 18:
    print("You can vote")

temperature = 38
if temperature > 37:
    print("Fever detected, see a doctor")
    print("Stay hydrated")

▶ Output

You can vote
Fever detected, see a doctor
Stay hydrated

What happened here: The colon after if age >= 18: opens the block. Everything indented under it runs only when the condition is True. Both print lines under the temperature check run because they sit at the same indentation, so Python treats them as one block. This is the part that trips up newcomers: indentation is not just for looks in Python. It IS the syntax. The spaces are doing the same job that curly braces do in other languages.

if-else: Two Paths

A plain if only handles the yes case. Real decisions usually need both outcomes covered. Think of if-else as a fork in the road: your program always takes exactly one of the two paths, never both, never neither. Say a student named Rahul just got his exam result and the pass mark is 60. His score decides which message prints.

📄 if_else.py: when you need both outcomes handled

rahul_score = 72

if rahul_score >= 60:
    print(f"Rahul passed with {rahul_score}%")
else:
    print(f"Rahul failed with {rahul_score}%")

# Numbers are truthy/falsy too
items_in_cart = 0
if items_in_cart:
    print(f"You have {items_in_cart} items")
else:
    print("Your cart is empty")

▶ Output

Rahul passed with 72%
Your cart is empty

What happened here: The else block runs whenever the if condition turns out False. There is no condition to fail, so it is the safety net. Look closely at the cart check: if items_in_cart: works because 0 counts as falsy in Python, so you never have to write the longer if items_in_cart != 0:. That little shortcut shows up everywhere, and the truthy and falsy section below explains exactly why it works.

if-elif-else: Multiple Paths

When there are more than two outcomes, elif joins in. It works like the fare slabs at a railway ticket counter: the clerk checks your ticket against each slab from the top and charges you the first one that fits, then stops looking. Here four students, Niranjan, Viraj, Pravin, and Anvay, get letter grades based on where their scores land.

Quick heads-up: the first two lines use a dictionary and a for loop to walk through the four scores. Both are previews here and get their own full lessons soon (for loops and dictionaries), so do not worry about parsing them yet. Keep your eyes on the if-elif-else chain in the middle.

📄 grading.py: many conditions with elif

students = {"Niranjan": 92, "Viraj": 85, "Pravin": 68, "Anvay": 45}

for name, score in students.items():
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    elif score >= 70:
        grade = "C"
    elif score >= 60:
        grade = "D"
    else:
        grade = "F"
    print(f"{name}: {score}% → Grade {grade}")

▶ Output

Niranjan: 92% → Grade A
Viraj: 85% → Grade B
Pravin: 68% → Grade D
Anvay: 45% → Grade F

What happened here: Python checks the conditions top to bottom and stops at the first True. Niranjan’s 92 matches score >= 90 straight away, so it lands on grade “A” and never bothers checking the rest. Pravin’s 68 is the interesting one: it fails the >= 70 test, drops to the next slab, and lands on “D”, because the chain always settles on the first passing check, not the grade your school intuition expects. This is the reason order matters so much. If you put score >= 60 at the top instead, everyone who passed would get a “D”, because 60 catches them before 90 ever gets a look. Always list your narrowest condition first.

Nested Conditions

Sometimes one decision only makes sense after another has already passed. Nested conditions are like airport checkpoints: you only reach the boarding gate after clearing security, and you only reach security after showing your ticket. In code, each inner if sits indented inside the block of the outer one.

📄 nested.py: conditions inside conditions

age = 28
has_license = True
has_insurance = False

if age >= 18:
    if has_license:
        if has_insurance:
            print("You can drive")
        else:
            print("Get insurance first")
    else:
        print("Get a license first")
else:
    print("Too young to drive")

# Better: flatten with 'and'
if age >= 18 and has_license and has_insurance:
    print("\nFlattened: You can drive")
else:
    print("\nFlattened: Missing requirements")

▶ Output

Get insurance first

Flattened: Missing requirements

What happened here: Nested conditions work, but they get ugly fast. Once you are three levels of indentation deep, your code is drifting off the right edge of the screen and is hard to follow. The flattened version with and says the same thing in one line and reads far better. So when should you nest? Only when each branch needs its own message, like the driving example, where “get a license” and “get insurance” are genuinely different advice. If all you want is a single yes-or-no answer, flatten it with and or or.

Truthy and Falsy Values

Python does not insist that the condition be a real boolean. Any value at all works inside an if. Python quietly treats some values as “falsy” (they behave like False) and treats everything else as “truthy.” The easy way to remember it: anything that means “empty” or “nothing” is falsy. An empty list, an empty string, the number zero, None. It is like checking your wallet. If there is nothing in it, the answer is “no money,” and that counts as False. (The demo below uses lists and a for loop to print each value in one go. Both are previews with full lessons coming up, so just read the output for now.)

📄 truthy_falsy.py: what Python counts as True and False

# All FALSY values (these act like False)
falsy_values = [False, None, 0, 0.0, 0j, "", [], (), {}, set(), frozenset()]

print("Falsy values:")
for val in falsy_values:
    print(f"  {str(val):<15} → bool: {bool(val)}")

# Everything else is TRUTHY
print("\nTruthy examples:")
truthy_values = [True, 1, -1, 0.001, "hello", [0], {"key": "val"}]
for val in truthy_values:
    print(f"  {str(val):<15} → bool: {bool(val)}")

# Practical usage: check if the signup list has anyone in it
names = ["Aditi", "Anvi"]
if names:
    print(f"\nFirst person: {names[0]}")

▶ Output

Falsy values:
  False           → bool: False
  None            → bool: False
  0               → bool: False
  0.0             → bool: False
  0j              → bool: False
                  → bool: False
  []              → bool: False
  ()              → bool: False
  {}              → bool: False
  set()           → bool: False
  frozenset()     → bool: False

Truthy examples:
  True            → bool: True
  1               → bool: True
  -1              → bool: True
  0.001           → bool: True
  hello           → bool: True
  [0]             → bool: True
  {'key': 'val'}  → bool: True

First person: Aditi

What happened here: bool(val) shows you the truth value Python would use for each item inside an if. Every “empty” thing came back False, including the empty string, the empty list, the empty tuple, the empty dict, an empty set, and zero in all its forms (0, 0.0, 0j). Notice that [0] is truthy even though the only item it holds is zero. The list is not empty, so it is truthy. That is the catch people miss: it is the container that is checked, not what is inside it. So if names: is the clean, idiomatic way to ask “does this list have anything in it?”

Combining Conditions

Single conditions rarely cut it in real code. Think of and as a bank locker that needs two keys turned together, or as a hall with two doors where entering through either one gets you in, and not as a switch that flips the answer. Python spells all three as plain English words, no && or || symbols to memorise.

📄 logical_operators.py: and, or, not

age = 25
experience = 3
has_degree = True

# and: both must be True
if age >= 21 and experience >= 2:
    print("Eligible for senior role")

# or: at least one must be True
if has_degree or experience >= 5:
    print("Meets education requirement")

# not: inverts the condition
is_banned = False
if not is_banned:
    print("Access granted")

# Chained comparisons, Python's superpower
score = 85
if 80 <= score <= 90:
    print(f"Score {score} is a B grade")

# This is equivalent to: if score >= 80 and score <= 90

▶ Output

Eligible for senior role
Meets education requirement
Access granted
Score 85 is a B grade

What happened here: The three little words do exactly what they say. and needs both sides to be true, or is happy with just one, and not flips the answer around. The real treat is the chained comparison 80 <= score <= 90. In most other languages you would have to write score >= 80 && score <= 90 and repeat the variable. Python lets you stack the comparisons the way you would on paper, and you can keep going: 0 < x < 10 < y < 100 is perfectly valid and reads just like maths class.

The Catch: Assignment vs Comparison

The way to keep the two symbols straight: = is a command (“make x equal 5”) while == is a question (“is x equal to 5?”). In C and JavaScript, a single = inside an if is one of the oldest bugs in the book. You meant to ask the question, you typed the command instead, and the condition silently assigns a new value and then judges that value, not the comparison you had in mind. Python simply refuses to play that game. Writing if x = 5: is a flat-out SyntaxError.

This is deliberate, and it quietly saves you from a whole family of bugs. If any of the comparison symbols still feel shaky, the Python operators guide walks through every one of them with tested examples.

📄 catch.py: Python protects you from a classic bug

x = 5

# This is comparison (correct)
if x == 5:
    print("x equals 5")

# if x = 5:    ← SyntaxError in Python!
# In C, this would silently assign 5 to x and always be True

# None check: always use 'is', not '=='
result = None
if result is None:
    print("No result yet")

▶ Output

x equals 5
No result yet

What happened here: The comparison x == 5 works, and the commented-out if x = 5: would stop the program before it ever ran. If you do slip and type a single =, Python 3.14.6 is genuinely helpful about it. The error reads SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?, so it even names the two operators you might have wanted. The second check, if result is None:, is the one habit to lock in early: always test for None with is, never with ==.

Common Mistakes

Mistake 1: Redundant boolean comparison

🚫 Redundant

is_active = True
if is_active == True:    # comparing a bool to True is pointless
    print("Active")

✅ Clean

is_active = True
if is_active:            # the variable IS already a boolean
    print("Active")

Mistake 2: elif order that never reaches later branches

🚫 Wrong order

score = 95
if score >= 60:      # catches everything >= 60
    grade = "D"      # 95 gets grade D!
elif score >= 90:    # never reached for high scores
    grade = "A"

✅ Correct order

score = 95
if score >= 90:      # most specific first
    grade = "A"
elif score >= 60:    # broader condition after
    grade = "D"

Best Practices

  • DO use truthy/falsy checks for emptiness: if names: not if len(names) > 0:
  • DO use chained comparisons: if 0 < x < 100:
  • DO check None with is: if result is None:
  • DO put the most specific elif conditions first
  • DON’T write if x == True:. Just use if x:
  • DON’T nest more than 3 levels deep. Flatten with and/or, or use early returns

Conclusion

The Python if else structure gives your code the ability to make decisions. if checks a condition. elif adds alternatives. else catches everything that fell through. Python evaluates top to bottom and runs only the first matching block. Truthy and falsy values let you write clean, idiomatic checks without explicit comparisons to True, False, 0, or empty containers.

Next up: Ternary Operator and Short-Circuit Evaluation. You will learn the inline one-line conditions and the and/or tricks that squeeze a whole Python if else block down to a single tidy expression.

This post is one chapter of a much bigger, completely free journey from Python basics to machine learning. Browse every chapter on the Python + AI/ML tutorial series home and pick up wherever you left off.

Practice Exercises

  1. Exercise 1: Print whether a number is positive, negative, or zero.
  2. Exercise 2: Create a grade calculator (0-100 to letter grade).
  3. Exercise 3: Build a tax calculator with 4 brackets.

Frequently Asked Questions

What is the difference between if and elif in Python?

if starts a new conditional check. elif (else-if) provides an additional condition that is only checked when all previous if and elif conditions were False. Only one block in an if/elif/else chain ever executes.

What are truthy and falsy values in Python?

Falsy values are: False, None, 0, 0.0, '' (empty string), [] (empty list), () (empty tuple), {} (empty dict), and set(). Everything else is truthy. Python automatically converts values to boolean in if conditions.

Can I chain comparisons in Python?

Yes. Python supports chained comparisons like 0 < x < 100, which is equivalent to x > 0 and x < 100 but more readable. You can chain any number of comparisons: a < b < c < d is valid Python.

How many elif statements can I have?

There is no limit on the number of elif statements. However, if you have more than 5-6 conditions, consider using a dictionary mapping or match/case (Python 3.10+) instead, which is more readable.

Why should I use is instead of == for None?

None is a singleton object, meaning there is exactly one None in any Python program. is checks identity (same object in memory), which is faster and cannot be fooled by a custom __eq__ method. PEP 8 (Python Enhancement Proposal 8) explicitly recommends is None over == None.

Interview Questions on Python if else

Try each one aloud first. The phrasing you produce under mild pressure is what interviews measure.

Q: Why does Python raise an error for if x = 5: when C happily compiles the equivalent code?

Python treats assignment as a statement, not an expression, so a bare = inside a condition is a SyntaxError caught before the program even runs. In C, if (x = 5) assigns 5 to x and evaluates the assigned value as the condition, which creates silent bugs. Python 3.14.6 even suggests the fix in its error message: it asks whether you meant == or :=.

Q: Your grading function returns "D" for a student who scored 95. The elif chain looks complete. What do you check first?

Check the order of the conditions. If score >= 60 appears before score >= 90, a 95 matches the broader condition first and Python never reaches the "A" branch, because an if/elif chain stops at the first True. The fix is to list the most specific (highest) threshold first and let the broader ones follow.

Q: You read a user's age with input() and the line if age >= 18: crashes with TypeError: '>=' not supported between instances of 'str' and 'int'. What went wrong?

input() always returns a string, even when the user types digits, so you are comparing "25" against the integer 18. Convert first with age = int(input("Age: ")), ideally inside a try/except to handle non-numeric input. The condition itself is fine; the data type feeding it is not.

Q: What is the difference between if not x: and if x is None:?

if x is None: is true only when x is literally the None object. if not x: is true for every falsy value: None, but also 0, 0.0, "", empty lists, and empty dicts. The distinction bites when 0 or an empty string is a legitimate value, for example a temperature reading of 0 degrees would wrongly be treated as "missing" by if not x:. Use is None when you specifically mean "no value was set."

Q: What is short-circuit evaluation in Python's and and or?

Python stops evaluating a boolean expression as soon as the result is known. In a and b, if a is falsy, b is never evaluated; in a or b, if a is truthy, b is skipped. This is useful as a guard: if divisor != 0 and total / divisor > 10: never raises ZeroDivisionError because the division only runs when the first check passes.

Q: A code review flags your function for having four levels of nested if statements. How would you refactor it?

Two standard moves. First, if the branches all funnel into one outcome, flatten them into a single condition with and: if age >= 18 and has_license and has_insurance:. Second, use guard clauses, meaning early returns for the failure cases at the top of the function (if age < 18: return "too young"), so the main logic stays at one indentation level. Keep genuine nesting only when each branch needs its own distinct handling.

Go deeper: when you outgrow this post, the official Python documentation is the next stop.

Previous: Python: Taking User Input with input(), Type Casting, Validation

Next: Python: Ternary Operator & Short-Circuit Evaluation

Series Home: Python + AI/ML Tutorial Series

RahulAuthor posts

Avatar for Rahul

Rahul is a passionate IT professional who loves to sharing his knowledge with others and inspiring them to expand their technical knowledge. Rahul's current objective is to write informative and easy-to-understand articles to help people avoid day-to-day technical issues altogether. Follow Rahul's blog to stay informed on the latest trends in IT and gain insights into how to tackle complex technical issues. Whether you're a beginner or an expert in the field, Rahul's articles are sure to leave you feeling inspired and informed.

No comment

Leave a Reply

Your email address will not be published. Required fields are marked *