Skip to content
Home Python if-elif-else in Python

if-elif-else in Python

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Control Flow → Topic 1 of 7
Python if-elif-else statements — syntax, comparison operators, truthy and falsy values, nested conditions, ternary expressions, and match-case in Python 3.
🧑‍💻 Beginner-friendly — no prior Python experience needed
In this tutorial, you'll learn
Python if-elif-else statements — syntax, comparison operators, truthy and falsy values, nested conditions, ternary expressions, and match-case in Python 3.
  • Python uses elif, not else if — else if creates a nested else block, which is valid but rarely what you mean.
  • Indentation defines the block — be consistent with 4 spaces (PEP 8 standard).
  • Python evaluates many things as falsy: None, 0, '', [], {} — learn the list to write cleaner conditions.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Python uses if, elif, and else for conditional branching. Indentation defines the block — no curly braces. Use elif for additional conditions (not else if). Python also has a one-line ternary expression: value_if_true if condition else value_if_false.

Basic if-elif-else

Example · PYTHON
12345678910111213141516171819
# Package: io.thecodeforge.python.control_flow

score = 73

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'Score {score} → Grade {grade}')  # Score 73 → Grade C

# Conditions are checked top to bottom — first True wins
# Once a branch executes, the rest are skipped
▶ Output
Score 73 → Grade C

Truthy and Falsy Values

Python evaluates any object in a boolean context. Knowing what is falsy saves you from writing verbose comparisons.

Example · PYTHON
123456789101112131415161718192021222324
# Falsy values — evaluate to False in a boolean context
falsy_examples = [
    False, 0, 0.0, 0j,       # false booleans and zeros
    '', [], {}, set(), (),    # empty sequences and collections
    None,                     # the None singleton
]

for val in falsy_examples:
    if not val:
        print(f'{repr(val):10} is falsy')

# In practice:
name = input('Enter name: ')  # imagine user entered ''
if name:  # cleaner than: if name != ''
    print(f'Hello, {name}')
else:
    print('No name provided')

# Common pitfall: 0 is falsy
count = 0
if count:  # This is False — but count is a valid value!
    print('Has items')
# Better:
if count is not None:  # only check for missing, not zero
▶ Output
False is falsy
0 is falsy
0.0 is falsy
'' is falsy
[] is falsy

Ternary Expression

Python's ternary is the reverse of most languages — condition comes in the middle, not at the start.

Example · PYTHON
1234567891011121314151617
age = 20

# Ternary: value_if_true if condition else value_if_false
status = 'adult' if age >= 18 else 'minor'
print(status)  # adult

# Common uses
temperature = -5
description = 'freezing' if temperature < 0 else 'warm' if temperature < 20 else 'hot'
print(description)  # freezing

# Conditional assignment (also works, but less expressive)
max_val = a if a > b else b  # same as max(a, b)

# Do NOT use for complex logic — readability drops fast
# This is too much for one line:
# result = 'a' if x > 0 else 'b' if x < 0 else 'c' if x == 0 else 'd'
▶ Output
adult
freezing

match-case — Python 3.10+

Python 3.10 added structural pattern matching. It is more powerful than a chain of elif — it can match on structure, not just equality.

Example · PYTHON
12345678910111213141516171819202122232425
def http_status(code: int) -> str:
    match code:
        case 200: return 'OK'
        case 201: return 'Created'
        case 400: return 'Bad Request'
        case 401 | 403: return 'Auth error'  # multiple values with |
        case 404: return 'Not Found'
        case 500: return 'Internal Server Error'
        case _: return f'Unknown status: {code}'  # default

print(http_status(200))  # OK
print(http_status(403))  # Auth error
print(http_status(999))  # Unknown status: 999

# Structural matching on tuples
def describe_point(point):
    match point:
        case (0, 0): return 'Origin'
        case (x, 0): return f'On x-axis at {x}'
        case (0, y): return f'On y-axis at {y}'
        case (x, y): return f'Point at ({x}, {y})'

print(describe_point((0, 0)))   # Origin
print(describe_point((3, 0)))   # On x-axis at 3
print(describe_point((2, 5)))   # Point at (2, 5)
▶ Output
OK
Auth error
Unknown status: 999
Origin
On x-axis at 3
Point at (2, 5)

🎯 Key Takeaways

  • Python uses elif, not else if — else if creates a nested else block, which is valid but rarely what you mean.
  • Indentation defines the block — be consistent with 4 spaces (PEP 8 standard).
  • Python evaluates many things as falsy: None, 0, '', [], {} — learn the list to write cleaner conditions.
  • Ternary syntax: value_if_true if condition else value_if_false.
  • Python 3.10+ match-case is not just a switch statement — it does structural pattern matching.

Interview Questions on This Topic

  • QWhat values are considered falsy in Python?
  • QWhat is the difference between elif and a nested if-else?
  • QWhat is the syntax for a ternary expression in Python?

Frequently Asked Questions

What is the difference between elif and else if in Python?

elif is the correct keyword — it checks a new condition only if all previous conditions were False. Writing else if creates two separate statements: an else block containing a standalone if. Both work, but elif is correct and elif chains are compiled more efficiently.

Can a Python if statement have no else?

Yes. The else clause is optional. If the condition is False and there is no else, Python simply moves on to the next line after the if block. This is fine — you only need else when you have something specific to do in the False case.

Is Python's match-case the same as a switch statement?

It is more powerful. A traditional switch statement matches on a single value. Python's match-case can match on value, type, structure (tuples, lists, dicts), guard conditions (case x if x > 0), and class attributes. Think of it as destructuring + conditional in one.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

Next →for Loop in Python
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged