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.
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.
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:
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."
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 simplest conditional is a standalone if statement. It says: "If this condition is true, do something."
# 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.
# 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
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.
# 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.
When you have more than two possibilities, use elif (short for "else if"). This lets you check multiple conditions in sequence.
# 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.
You can combine multiple checks in a single condition using and, or, and not.
# 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.
# 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.")
Let's build a program that converts numerical scores to letter grades. This is a perfect exercise for practicing if-elif-else statements.
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): "))
# 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}")
# 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}")
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.
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.
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.
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.
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 (:).
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.
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.
Project Goal: Build a secure login system that validates usernames and passwords.
# 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.")
# 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.")
💡 Hint: For case-insensitive comparison, use the .lower() method: if username.lower() == correct_user.lower():
You've mastered the decision-making structures in Python! Here's what you now know:
and, or, not) let you combine conditionsNow that you can make decisions, you're ready to repeat actions with loops. Here's your action plan:
and/or🚀 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!
Check your understanding with this quick quiz
1. What will this code print if age = 16?if age >= 18:
print("Adult")
else:
print("Minor")
2. Which symbol must appear at the end of every if/elif/else line?
3. How many blocks can execute in an if-elif-else statement?
4. What's wrong with this code?if score >= 90:
print("A")
5. What does this condition check?if age >= 18 and has_license:
6. Which order should you check grade conditions?