← View series: python tutorials
~/blog
Control Flow - Conditionals
Introduction
In this tutorial, you'll learn how to make decisions in your Python programs using conditionals. Conditionals allow your code to execute different blocks of code based on certain conditions - this is what makes programs "smart" and able to respond to different situations.
What You'll Learn
- The
ifstatement - The
elifstatement (else if) - The
elsestatement - Nested conditionals
- Comparison operators in conditionals
- Logical operators for complex conditions
The if Statement
The if statement is the most basic conditional. It executes code only when a condition is True:
# Basic if statement
age = 18
if age >= 18:
print("You are an adult!")
print("You can vote.")
print("Program continues...")Output:
You are an adult!
You can vote.
Program continues...
Indentation is Key
In Python, indentation (spaces at the beginning of lines) defines code blocks. The code inside an if statement must be indented:
# Correct indentation
if age >= 18:
print("Adult") # This is inside the if block
print("Can vote") # This is also inside
print("Outside if") # This runs regardless⚠️ Warning: Mixing tabs and spaces can cause errors. Use spaces consistently (4 spaces is standard).
The else Statement
The else block runs when the if condition is False:
age = 15
if age >= 18:
print("You are an adult!")
else:
print("You are a minor.")Output:
You are a minor.
The elif Statement
Use elif (short for "else if") to check multiple conditions:
score = 85
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"Your grade is: {grade}")Output:
Your grade is: B
How elif Works
Python evaluates conditions in order from top to bottom:
- Checks
ifcondition → if True, executes and skips rest - Checks first
elif→ if True, executes and skips rest - Checks second
elif→ and so on... - If nothing matched, executes
elseblock
Practical Examples
Example 1: Simple Login Check
username = "admin"
password = "secret123"
if username == "admin" and password == "secret123":
print("Login successful!")
else:
print("Invalid username or password.")Example 2: Temperature Warning
temperature = 95
if temperature > 40:
print("🔥 Extreme heat warning! Stay hydrated.")
elif temperature > 30:
print("☀️ It's hot today!")
elif temperature > 20:
print("🌤️ Pleasant weather")
elif temperature > 10:
print("❄️ It's getting cold")
else:
print("🥶 It's cold! Bundle up!")Example 3: Leap Year Checker
year = 2024
# A year is a leap year if divisible by 4
# but not by 100, unless also divisible by 400
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year!")
else:
print(f"{year} is not a leap year.")Output:
2024 is a leap year!
Nested Conditionals
You can nest conditionals inside each other:
age = 25
has_license = True
if age >= 18:
print("You can potentially drive.")
if has_license:
print("And you have a license! Drive safely!")
else:
print("But you need to get a license first.")
else:
print("You're too young to drive.")When to Use Nested Conditionals
Use nesting when you need to check a second condition only if the first is true. However, avoid nesting too deep (3+ levels) as it becomes hard to read.
Complex Conditions with Logical Operators
Combine multiple conditions using and, or, and not:
Using and
age = 25
income = 50000
if age >= 18 and income > 30000:
print("You qualify for the loan!")Using or
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")Using not
is_raining = False
if not is_raining:
print("You can go outside!")Ternary Operator (Conditional Expression)
Python has a compact way to write simple conditionals:
# Traditional way
age = 20
if age >= 18:
status = "Adult"
else:
status = "Minor"
# Ternary operator (one-liner)
status = "Adult" if age >= 18 else "Minor"This is useful for simple assignments but avoid using it for complex logic.
Summary
In this tutorial, you learned:
- ✅ The
ifstatement for basic conditional execution - ✅ The
elseblock for when conditions are false - ✅ The
elifstatement for multiple conditions - ✅ Nested conditionals for complex logic
- ✅ Using logical operators (
and,or,not) - ✅ Ternary operator for compact conditionals
🧑💻 Practice Exercise
Create a program that:
- Asks the user for their age
- Asks if they have a job (yes/no)
- Based on age and job status, prints:
- If under 16: "You're too young to work"
- If 16-18 and has job: "Great! You're employed"
- If 16-18 and no job: "Time to find a job!"
- If over 18 and has job: "Adult with responsibilities!"
- If over 18 and no job: "Time to find a job!"
Click to see solution
# Job eligibility checker
age = int(input("Enter your age: "))
has_job = input("Do you have a job? (yes/no): ").lower() == "yes"
print("\n--- Result ---")
if age < 16:
print("You're too young to work.")
elif age <= 18:
if has_job:
print("Great! You're employed.")
else:
print("Time to find a job!")
else:
if has_job:
print("Adult with responsibilities!")
else:
print("Time to find a job!")What's Next
In the next tutorial, we'll learn about Control Flow - Loops - how to repeat actions efficiently.