Skip to main content

Conditional Structures in Python with if, elif and else

So far, all our code has run from start to finish without any deviations. But in real life, programs need to make decisions. What if the user enters an incorrect password? What if the temperature exceeds 30 degrees? This is where conditional structures come in.

Conditionals are the heart of logic in programming. They allow you to execute different blocks of code depending on whether certain conditions are met or not. In Python, this is achieved with the keywords if, elif, and else.

The if statement: the simplest decision

The most basic structure is if. It evaluates a condition and, if it is True, executes the indented block of code below it.

Python
age = 18

if age >= 18:
print("You are an adult")

Key fact: In Python, indentation is not optional. It defines which block of code belongs to each condition. By convention, we use 4 spaces (not tabs) for indentation.

The alternative path: else

What happens if the condition is not met? That's where else comes in. It has no condition of its own; it runs when if is false.

Python
age = 15

if age >= 18:
print("You can enter the site")
else:
print("Sorry, you must be 18 or older")

Multiple paths: elif

When you need to evaluate more than two possibilities, you use elif (short for "else if"). Python evaluates the conditions in order and executes the block of the first true condition it finds.

Python
score = 85

if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"

print(f"Your grade is: {grade}")
DivZone ad link Logo
AI PlatformTurn Code into Customers.Try it free

Nested conditions

You can place an if inside another if. This is called nesting and is useful when you need to check multiple levels of conditions.

Python
user_authenticated = True
is_admin = False

if user_authenticated:
print("Welcome to the system")

if is_admin:
print("You have full access")
else:
print("You have limited access")
else:
print("Please log in")

Warning: Do not nest more than 2 or 3 levels. If you need to, your code becomes hard to read. In those cases, consider using functions or restructuring the logic.

The ternary conditional (ternary operator)

Python offers a compact way to write a simple if-else in a single line. It's ideal for quick assignments.

Python
# Traditional way
if temperature > 30:
message = "It's hot"
else:
message = "It's cool"

# Ternary way (one line)
message = "It's hot" if temperature > 30 else "It's cool"

The syntax is: value_if_true if condition else value_if_false.

The match statement (Python 3.10+)

Starting from Python 3.10, you can use match and case to create more elegant conditional structures when working with multiple fixed values. It is similar to switch in other languages.

Python
command = "exit"

match command:
case "start":
print("Starting the system...")
case "stop":
print("Stopping the system...")
case "pause":
print("Pausing the system...")
case "exit":
print("Exiting the system...")
case _:
print("Unknown command")

The underscore _ acts as the default case, catching any value that does not match the previous cases.

Common mistakes (and how to avoid them)

Forgetting the colon (:)

Python
# ❌ Error: missing colon
if age >= 18
print("Adult")

# ✅ Correct
if age >= 18:
print("Adult")

Incorrect indentation

Python
# ❌ Error: inconsistent indentation
if age >= 18:
print("Adult")
print("This code is misindented")

# ✅ Correct: consistent 4 spaces
if age >= 18:
print("Adult")
print("This code also belongs to the if")

Using = instead of ==

Python
# ❌ Error: = assigns, does not compare
if age = 18:
print("You are 18 years old")

# ✅ Correct: == compares
if age == 18:
print("You are 18 years old")

Redundant conditions

Python
# ❌ Redundant: bool is already True or False
if is_adult == True:
print("Adult")

# ✅ Correct and more readable
if is_adult:
print("Adult")

Summary table of conditional structures

StructureSyntaxWhen to use it
Simple ifif condition:A single condition
if-elseif condition: else:Two possible paths
if-elif-elseif cond1: elif cond2: else:Multiple chained conditions
Ternary conditionalvalue if cond else other_valueSimple one-line assignment
match-casematch value: case pattern:Multiple fixed values (Python 3.10+)
Nestedif cond1: if cond2:Conditions at multiple levels

Practical challenge: "Grade Calculator"

Write a program that asks the user for their score (0 to 100) and displays their grade according to this table:

ScoreGrade
90 - 100A (Excellent)
80 - 89B (Good)
70 - 79C (Satisfactory)
60 - 69D (Sufficient)
0 - 59F (Insufficient)

Additional requirements:

  • If the score is outside the 0-100 range, display an error message.
  • If the score is exactly 100, add a special message: "Perfect score!"
Python
# Test variable
score = 85

# Your logic here
# ...

Hint: Use elif to evaluate ranges in descending order (from highest to lowest). This way you avoid having to check both range boundaries.

tip

In Python, you can write conditions like if score >= 90: without needing to write if score >= 90 and score <= 100: when evaluating in descending order. Python executes the first if that is true and skips the rest, so if you reach elif score >= 80: you already know that score is less than 90.

Resources

Ready to continue? Explore more Python topics in the Python course index.

Want to put what you learned to the test? Use DivZone AI to generate and test your own conditional exercises.