Beginner

Conditional Statements in Python

Learn to make decisions in your code with if, elif, and else

Should your app send a discount code? Is the user old enough to create an account? Does the password match? Every meaningful program needs to make decisions, and that's exactly what conditional statements do. They're the decision-making brain of your code, allowing your programs to respond differently based on different situations. In this tutorial, you'll learn how to use if, elif, and else to build programs that think.

What Are Conditional Statements?

Conditionals are code structures that run different blocks of code based on whether a condition is true or false. Think of them as decision points in your program—like a choose-your-own-adventure book where the story branches based on your choices.

You've already learned about comparison operators (>, ==, !=) and logical operators (and, or, not) that produce True or False values. Conditionals use these boolean values to decide which code to execute.

Why Are Conditionals Essential?

Without conditionals, your programs would be completely linear—they'd execute the same code every single time, regardless of input or circumstances. Conditionals give your programs:

The Perfect Analogy: Traffic Lights

Think of conditionals like a traffic light system. When you approach an intersection:

Your program checks each condition in order, just like you check the traffic light. Once it finds a true condition, it executes that block of code and moves on. If no conditions are true, it falls back to the "else" block—the red light that says "do this by default."

Visual Mental Model

How Conditionals Flow:

if condition:
    # Execute this if condition is True
    ...
elif other_condition:
    # Execute this if first was False, this is True
    ...
else:
    # Execute this if all above were False
    ...

Decision Flow:
Check condition → True? Execute → Skip rest
Check condition → False? Move to next → Repeat
All False? → Execute else block

Notice the pattern: Python checks each condition from top to bottom. The moment it finds a true condition, it executes that block and skips all the rest. If nothing is true, the else block runs as a fallback.

The Basic if Statement

The simplest conditional is a standalone if statement. It says: "If this condition is true, do something."

Example 1: Simple Age Check

# Check if user is an adult
age = 25

if age >= 18:
    print("You are an adult.")
    print("You can create a full account.")

print("Thank you for visiting!")  # This always runs

Output:

You are an adult.
You can create a full account.
Thank you for visiting!

💡 Critical Detail: Notice the indentation! The two print statements under if are indented by 4 spaces. This tells Python they belong to the if block. The last print statement is NOT indented, so it runs regardless of the condition.

Example 2: Conditional Discount

# Apply discount for large orders
total = 150

if total >= 100:
    print("Congratulations! You qualify for a 10% discount.")
    discount = total * 0.10
    total = total - discount
    print(f"Your new total: ${total:.2f}")

Output:

Congratulations! You qualify for a 10% discount.
Your new total: $135.00

The if-else Statement

Often, you want to do one thing if a condition is true, and something different if it's false. That's where else comes in.

Example 3: Account Type Decision

# Determine account type based on age
age = int(input("Enter your age: "))

if age >= 18:
    print("Adult account created.")
    print("Full features unlocked.")
else:
    print("Child account created.")
    print("Parental controls enabled.")

print("Welcome to our platform!")

If you enter 25:

Adult account created.
Full features unlocked.
Welcome to our platform!

If you enter 12:

Child account created.
Parental controls enabled.
Welcome to our platform!

⚠️ Important: Only ONE of the blocks will execute—either the if block OR the else block, never both. The final print statement always runs because it's not indented under either block.

The if-elif-else Statement

When you have more than two possibilities, use elif (short for "else if"). This lets you check multiple conditions in sequence.

Example 4: Three-Way Account System

# Create age-appropriate accounts
age = int(input("Enter your age: "))

if age >= 18:
    print("Adult account created.")
    print("All features available.")
elif age >= 13:
    print("Teen account created.")
    print("Some restrictions apply.")
else:
    print("Child account created.")
    print("Heavy parental controls active.")

print("\nAccount setup complete!")

Let's see what happens with different ages:

Age 25:

Adult account created.
All features available.

Account setup complete!

Age 15:

Teen account created.
Some restrictions apply.

Account setup complete!

Age 8:

Child account created.
Heavy parental controls active.

Account setup complete!

💡 How it works: Python checks age >= 18 first. If false, it checks age >= 13. If that's also false, it executes the else block. Only ONE block ever runs.

Multiple Conditions with Logical Operators

You can combine multiple checks in a single condition using and, or, and not.

Example 5: Login System

# Simple login validation
correct_username = "admin"
correct_password = "secret123"

username = input("Username: ")
password = input("Password: ")

if username == correct_username and password == correct_password:
    print("Welcome! Login successful.")
    print("Access granted to dashboard.")
else:
    print("Invalid credentials.")
    print("Access denied.")

Both conditions must be true for login to succeed. If either the username OR password is wrong, access is denied.

Example 6: Eligibility Checker

# Check driving eligibility
age = 17
has_license = True
has_insurance = False

if age >= 18 and has_license and has_insurance:
    print("You can drive legally.")
elif age >= 18 and has_license:
    print("You can drive but need insurance first.")
elif age >= 18:
    print("You need a license and insurance.")
else:
    print("You must be 18 or older to drive.")

Hands-On Exercise: Grade Classifier

Let's build a program that converts numerical scores to letter grades. This is a perfect exercise for practicing if-elif-else statements.

Requirements

Step 1: Get the Score

Create a file called grade_classifier.py:

# Grade Classifier
print("=== Grade Classifier ===\n")

# Get student's score
score = int(input("Enter your score (0-100): "))

Step 2: Add the Conditional Logic

# Classify the grade
if score >= 90:
    grade = "A"
    message = "Excellent work!"
elif score >= 80:
    grade = "B"
    message = "Good job!"
elif score >= 70:
    grade = "C"
    message = "Satisfactory."
elif score >= 60:
    grade = "D"
    message = "Needs improvement."
else:
    grade = "F"
    message = "Failing. Please seek help."

Step 3: Display the Result

# Show the results
print(f"\nYour score: {score}")
print(f"Your grade: {grade}")
print(f"Comment: {message}")

Complete Code

# Grade Classifier
print("=== Grade Classifier ===\n")

# Get student's score
score = int(input("Enter your score (0-100): "))

# Classify the grade
if score >= 90:
    grade = "A"
    message = "Excellent work!"
elif score >= 80:
    grade = "B"
    message = "Good job!"
elif score >= 70:
    grade = "C"
    message = "Satisfactory."
elif score >= 60:
    grade = "D"
    message = "Needs improvement."
else:
    grade = "F"
    message = "Failing. Please seek help."

# Show the results
print(f"\nYour score: {score}")
print(f"Your grade: {grade}")
print(f"Comment: {message}")

Test Your Code

Run it with different scores:

Input: 95

=== Grade Classifier ===

Enter your score (0-100): 95

Your score: 95
Your grade: A
Comment: Excellent work!

Input: 73

=== Grade Classifier ===

Enter your score (0-100): 73

Your score: 73
Your grade: C
Comment: Satisfactory.

💡 Challenge: Add validation to ensure the score is between 0 and 100. If it's not, print an error message instead of classifying.

Common Mistakes to Avoid

❌ Mistake 1: Forgetting Indentation

Problem: Python throws an "IndentationError" or code doesn't execute as expected.

Why it happens: Python uses indentation to determine which code belongs to which block.

Solution:

# WRONG ❌
if age >= 18:
print("Adult")  # No indentation!

# CORRECT ✅
if age >= 18:
    print("Adult")  # Indented with 4 spaces

Prevention: Always indent code inside if/elif/else blocks by 4 spaces. Most code editors do this automatically when you press Tab.

❌ Mistake 2: Overlapping Conditions

Problem: The wrong condition executes because earlier conditions catch cases you didn't intend.

Why it happens: Python checks conditions from top to bottom and stops at the first true one.

Solution:

# WRONG ❌ - overlapping ranges
if score >= 60:
    grade = "D"
elif score >= 70:  # This will never run!
    grade = "C"

# CORRECT ✅ - most specific first
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"

Prevention: Order your conditions from most specific to least specific, or from highest to lowest values.

❌ Mistake 3: Using = Instead of ==

Problem: Your condition always evaluates to True, or you get an error.

Why it happens: Using a single = assigns a value; == compares values.

Solution:

# WRONG ❌
if password = "secret":  # This assigns, not compares!

# CORRECT ✅
if password == "secret":  # This compares

Prevention: Remember: = is for assignment, == is for comparison.

❌ Mistake 4: Forgetting the Colon

Problem: Python throws a "SyntaxError: invalid syntax".

Why it happens: Every if/elif/else line must end with a colon.

Solution:

# WRONG ❌
if age >= 18
    print("Adult")

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

Prevention: Always end conditional statements with a colon (:).

❌ Mistake 5: Illogical Conditions

Problem: Your condition can never be true.

Why it happens: Using "and" when you need "or", or vice versa.

Solution:

# WRONG ❌ - impossible condition
if age > 18 and age < 18:  # Can't be both!
    print("Teen")

# CORRECT ✅ - range check
if age >= 13 and age < 18:  # Between 13 and 17
    print("Teen")

# WRONG ❌ - too restrictive
if has_license and has_insurance:  # Must have both

# MAYBE CORRECT ✅ - depends on intent
if has_license or has_insurance:  # Has at least one

Prevention: Think through your logic: "and" means both must be true, "or" means at least one must be true.

❌ Mistake 6: Missing Edge Cases

Problem: Your program crashes or behaves unexpectedly for certain inputs.

Why it happens: Not considering all possible values or scenarios.

Solution:

# INCOMPLETE ❌
score = int(input("Score: "))
if score >= 90:
    grade = "A"
# What if score is negative? Or > 100?

# COMPLETE ✅
score = int(input("Score: "))
if score < 0 or score > 100:
    print("Invalid score! Must be 0-100.")
elif score >= 90:
    grade = "A"
# ... rest of conditions

Prevention: Always test edge cases: negative numbers, zero, maximum values, empty strings, etc.

Mini-Project: Login Simulation

Project Goal: Build a secure login system that validates usernames and passwords.

Requirements

Basic Implementation

# Simple Login System
print("=== Login System ===\n")

# Stored credentials
correct_user = "admin"
correct_pass = "secret123"

# Get user input
username = input("Username: ")
password = input("Password: ")

# Validate credentials
if username == correct_user and password == correct_pass:
    print("\n✓ Welcome! Login successful.")
    print("Access granted to dashboard.")
else:
    print("\n✗ Invalid credentials.")
    print("Access denied.")
    
    # Give specific feedback
    if username != correct_user:
        print("Hint: Username is incorrect.")
    if password != correct_pass:
        print("Hint: Password is incorrect.")

Enhanced Version with Attempt Tracking

# Login System with Attempt Tracking
print("=== Secure Login System ===\n")

# Stored credentials
correct_user = "admin"
correct_pass = "secret123"

# Track attempts
max_attempts = 3
attempts = 0

while attempts < max_attempts:
    # Get user input
    username = input("\nUsername: ")
    password = input("Password: ")
    
    # Validate credentials
    if username == correct_user and password == correct_pass:
        print("\n✓ Welcome! Login successful.")
        print("Access granted to dashboard.")
        break  # Exit the loop on success
    else:
        attempts += 1
        remaining = max_attempts - attempts
        
        print(f"\n✗ Invalid credentials.")
        
        if remaining > 0:
            print(f"You have {remaining} attempt(s) remaining.")
        else:
            print("Account locked due to too many failed attempts.")
            print("Please contact support.")

Bonus Challenges

  1. Multiple users: Store multiple username/password pairs and check against all of them
  2. Password strength: Check if password is at least 8 characters and contains a number
  3. Case-insensitive username: Accept usernames in any case (ADMIN, admin, Admin)

💡 Hint: For case-insensitive comparison, use the .lower() method: if username.lower() == correct_user.lower():

Summary: Key Takeaways

You've mastered the decision-making structures in Python! Here's what you now know:

What Makes Conditionals Powerful

Your Next Steps

Now that you can make decisions, you're ready to repeat actions with loops. Here's your action plan:

🚀 You're making real progress! Conditionals are where your programs start to feel intelligent. Combined with operators, you now have everything you need to build programs that think and decide. Next up: loops will let you repeat these decisions hundreds or thousands of times without writing repetitive code!

🎯 Test Your Knowledge: Conditional Statements

Check your understanding with this quick quiz

1. What will this code print if age = 16?
if age >= 18:
    print("Adult")
else:
    print("Minor")

Adult
Minor
Nothing
Error

2. Which symbol must appear at the end of every if/elif/else line?

;
:
.
None

3. How many blocks can execute in an if-elif-else statement?

All of them
Exactly one
None if all conditions are false
Two maximum

4. What's wrong with this code?
if score >= 90:
print("A")

Missing colon
Missing indentation
Wrong operator
Nothing wrong

5. What does this condition check?
if age >= 18 and has_license:

Either condition is true
Both conditions are true
Neither condition is true
Age is 18 or has license

6. Which order should you check grade conditions?

Lowest to highest (60, 70, 80, 90)
Highest to lowest (90, 80, 70, 60)
Random order is fine
Only use one condition
← Previous: Operators Next: Loops →