Technology  /  Python

🐍 Python 78 guides · updated 2026

From first variable to OOP, generators, and real projects — the language that runs everything from data pipelines to AI agents, taught the practical way.

Python if, elif, else: Conditional Logic That’s Readable at Any Complexity Level

Every useful program makes decisions. A login system checks credentials. A shopping cart applies discounts. A game checks whether the player has won. All of these decisions come down to the same basic mechanism: evaluate a condition and take different paths depending on whether it’s True or False.

The Basic Structure

temperature = 38
if temperature > 37.5:
print("Fever detected — rest and hydrate")
elif temperature >= 36.1:
print("Normal temperature")
else:
print("Temperature is low — consider seeing a doctor")

Python evaluates the conditions from top to bottom. The moment it finds one that’s True, it runs that block and skips the rest. If none match, else runs as the fallback.

A few rules:

Comparison and Logical Operators

age = 22
income = 35000
# Combine conditions with and / or / not
if age >= 18 and income >= 25000:
print("Eligible for loan")
if age < 18 or income < 10000:
print("Not eligible")
if not (age < 18):
print("Adult")
# Check membership
role = "editor"
if role in ("admin", "editor", "moderator"):
print("Has write access")

Short-circuit evaluation: Python stops evaluating as soon as the result is determined. In a and b, if a is False, Python never evaluates b. This matters when the second condition could raise an error if evaluated:

user = None
# Safe — short-circuit prevents AttributeError
if user is not None and user.is_active:
print("Active user")

Nested Conditions

Nesting if statements inside other if blocks handles cases with multiple independent conditions.

def classify_bmi(bmi):
if bmi < 18.5:
return "Underweight"
elif bmi < 25:
return "Normal"
elif bmi < 30:
return "Overweight"
else:
return "Obese"
# Nested: first check for a valid input
def process_bmi(weight_kg, height_m):
if height_m <= 0:
return "Invalid height"
else:
bmi = weight_kg / (height_m ** 2)
if bmi < 0 or bmi > 100:
return "Unrealistic BMI value"
else:
return classify_bmi(bmi)
print(process_bmi(70, 1.75)) # Normal
print(process_bmi(0, 0)) # Invalid height

Avoid nesting more than two or three levels deep. If you find yourself with deep nesting, consider extracting inner blocks into separate functions.

Ternary Expressions

For simple assignments, Python’s ternary (conditional) expression keeps things on one line:

# Syntax: value_if_true if condition else value_if_false
score = 75
grade = "Pass" if score >= 50 else "Fail"
print(grade) # Pass
# Commonly used in f-strings
count = 3
print(f"There {'is' if count == 1 else 'are'} {count} item{'s' if count != 1 else ''}")
# There are 3 items

Use ternary expressions when both options are short and clear. Avoid them for complex logic — a full if/else block is clearer.

The match Statement (Python 3.10+)

Python 3.10 introduced structural pattern matching with match. It is more powerful than a chain of elif comparisons because it can match against structures, not just values.

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)

match also works well for command parsing:

command = "quit"
match command.lower():
case "quit" | "exit" | "q":
print("Goodbye")
case "help" | "h":
print("Commands: quit, help, list")
case "list":
print("Listing items...")
case _: # default — like else
print(f"Unknown command: {command!r}")

Use match when you are dispatching on a known set of cases. For simple true/false decisions, if/elif is still the right tool.

Truthy and Falsy Values

Python considers more than just True and False in conditions. These values are all falsy (treated as False in a boolean context):

Everything else is truthy.

name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty") # prints this
items = []
if items:
print("Processing items...")
else:
print("Nothing to process") # prints this

This is idiomatic Python. Writing if len(items) == 0 works, but if not items is cleaner.

Common Logic Mistakes

Using = instead of ==. Assignment is =; comparison is ==. Python raises a SyntaxError if you write if x = 5:, but be careful with walrus operator (:=) which is intentional assignment inside conditions.

Relying on order when conditions overlap. Only the first matching branch runs. Make sure more specific conditions come before more general ones:

x = 15
# Wrong order
if x > 10:
print("Greater than 10") # this runs
elif x > 5:
print("Greater than 5") # never reached when x=15
# Correct: most specific first does not apply here — both are correct
# but make sure you understand which branch handles each case

Checking identity instead of equality. Use == for value comparison, is for identity (checking if two references point to the same object). x is None is correct (there is only one None); x is "hello" is unreliable.

x = None
if x is None: # correct
print("Empty")
if x == None: # works but non-idiomatic; avoid
print("Empty")