Back to blog
← View series: python tutorials

~/blog

Control Flow - Conditionals

Apr 1, 20264 min readBy Mohammed Vasim
PythonProgrammingTutorialBeginner

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 if statement
  • The elif statement (else if)
  • The else statement
  • 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:

python
# 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:

python
# 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:

python
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:

python
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:

  1. Checks if condition → if True, executes and skips rest
  2. Checks first elif → if True, executes and skips rest
  3. Checks second elif → and so on...
  4. If nothing matched, executes else block

Practical Examples

Example 1: Simple Login Check

python
username = "admin"
password = "secret123"

if username == "admin" and password == "secret123":
    print("Login successful!")
else:
    print("Invalid username or password.")

Example 2: Temperature Warning

python
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

python
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:

python
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

python
age = 25
income = 50000

if age >= 18 and income > 30000:
    print("You qualify for the loan!")

Using or

python
day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")

Using not

python
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:

python
# 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 if statement for basic conditional execution
  • ✅ The else block for when conditions are false
  • ✅ The elif statement 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:

  1. Asks the user for their age
  2. Asks if they have a job (yes/no)
  3. 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
python
# 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.

Control Flow - Loops →

Comments (0)

No comments yet. Be the first to comment!

Leave a comment