Python Programming Conditional Statements
Decision Making 4 Types

Python Conditional Statements Complete Guide

Learn Python conditional statements - simple if, if-else, elif ladder, and nested if with practical examples, flowcharts, and real-world applications for effective decision making.

Simple if

Single condition check

if-else

Two-way decision

elif Ladder

Multiple conditions

Nested if

Condition within condition

What are Conditional Statements?

Conditional statements allow your program to make decisions and execute different code blocks based on certain conditions. They are fundamental to controlling program flow in Python.

Key Concept

Conditional statements evaluate Boolean expressions (True or False) to decide which code blocks to execute. Python uses indentation (whitespace) to define code blocks.

Basic Conditional Statement Structure
# General syntax of conditional statements
if condition:
    # Code to execute if condition is True
    statement1
    statement2
elif another_condition:  # Optional (multiple can exist)
    # Code to execute if elif condition is True
    statement3
else:                    # Optional
    # Code to execute if all conditions are False
    statement4

# Note the colon (:) and indentation (4 spaces or 1 tab)

Python Conditional Statements Classification

Python conditional statements are classified into 4 main types. Each type serves a specific purpose in decision-making logic.

Complete Conditional Statements Reference Table

Type Syntax Description Best For Example
Simple if if condition: Executes a block only when condition is True Single condition check, execute or skip if age >= 18: print("Can vote")
if-else if-else Provides two alternative execution paths Two-way decisions, either-or scenarios if score >= 50: pass else: fail
elif Ladder if-elif-else Checks multiple conditions sequentially Multiple exclusive conditions, categorization if grade=='A': elif grade=='B': else:
Nested if if inside if Conditional statements inside other conditionals Hierarchical decisions, multi-stage validation if condition1: if condition2: ...
Quick Tip:
  • Use simple if for single condition checks
  • Use if-else for binary (true/false) decisions
  • Use elif ladder when you have multiple exclusive conditions
  • Use nested if for complex hierarchical decisions

Conditional Statement Examples with Output

Let's explore practical examples of each conditional statement type with actual Python code and output.

Simple if Statement Examples
# Simple if Statement Examples
print("=== Simple if Statement ===")

# Example 1: Check if number is positive
number = 10
if number > 0:
    print(f"{number} is a positive number")

# Example 2: Check voting eligibility
age = 18
if age >= 18:
    print("You are eligible to vote!")

# Example 3: String condition
password = "secure123"
if len(password) >= 8:
    print("Password meets minimum length requirement")

# Example 4: Multiple conditions with AND
temperature = 25
humidity = 60
if temperature > 20 and humidity < 70:
    print("Weather conditions are comfortable")
if-else Statement Examples
# if-else Statement Examples
print("\n=== if-else Statement ===")

# Example 1: Even or odd number check
number = 7
if number % 2 == 0:
    print(f"{number} is an even number")
else:
    print(f"{number} is an odd number")

# Example 2: Age verification for movie ticket
age = 16
if age >= 18:
    print("You can watch the movie (18+ rating)")
    print("Ticket price: $12")
else:
    print("Sorry, you are too young for this movie")
    print("Please choose a different movie")

# Example 3: Password validation
entered_password = "admin123"
correct_password = "admin123"
if entered_password == correct_password:
    print("Access granted!")
else:
    print("Access denied!")
elif Ladder Examples
# elif Ladder Examples
print("\n=== elif Ladder ===")

# Example 1: Grade calculation system
score = 78
if score >= 90:
    grade = "A"
    remark = "Excellent!"
elif score >= 80:
    grade = "B"
    remark = "Very Good!"
elif score >= 70:
    grade = "C"
    remark = "Good"
elif score >= 60:
    grade = "D"
    remark = "Pass"
else:
    grade = "F"
    remark = "Fail - Needs Improvement"

print(f"Score: {score}")
print(f"Grade: {grade}")
print(f"Remark: {remark}")

# Example 2: Temperature classification
temperature = 22
if temperature > 30:
    category = "Hot"
    advice = "Stay hydrated, avoid sun"
elif temperature > 20:
    category = "Warm"
    advice = "Perfect weather for outdoor activities"
elif temperature > 10:
    category = "Cool"
    advice = "Wear a light jacket"
elif temperature > 0:
    category = "Cold"
    advice = "Wear warm clothes"
else:
    category = "Freezing"
    advice = "Stay indoors if possible"

print(f"\nTemperature: {temperature}°C")
print(f"Category: {category}")
print(f"Advice: {advice}")
Nested if Statement Examples
# Nested if Statement Examples
print("\n=== Nested if Statement ===")

# Example 1: University admission system
has_diploma = True
grade_percentage = 85
entrance_exam_passed = True

if has_diploma:
    print("Candidate has required diploma")
    if grade_percentage >= 75:
        print("Grades meet minimum requirement (75%+)")
        if entrance_exam_passed:
            print("Entrance exam passed successfully")
            print("Congratulations! Admission granted.")
        else:
            print("Entrance exam not passed")
            print("Admission denied - Failed entrance exam")
    else:
        print(f"Grades insufficient: {grade_percentage}% (need 75%+)")
        print("Admission denied - Low grades")
else:
    print("No diploma certificate")
    print("Admission denied - Missing diploma")

# Example 2: Bank loan approval system
age = 35
income = 50000
credit_score = 750

if age >= 21:
    print("\nAge requirement satisfied")
    if income >= 30000:
        print("Income requirement satisfied")
        if credit_score >= 700:
            print("Credit score requirement satisfied")
            print("✓ Loan approved!")
        else:
            print(f"Credit score too low: {credit_score}")
            print("✗ Loan denied - Poor credit score")
    else:
        print(f"Income too low: ${income}")
        print("✗ Loan denied - Insufficient income")
else:
    print(f"\nToo young: {age} years (minimum 21)")
    print("✗ Loan denied - Age requirement not met")

Flowcharts and Decision Flow

Flowcharts help visualize how conditional statements control program flow. Understanding these visual representations is key to mastering decision-making in programming.

Flowchart: if-else Statement
Start
Condition True?
True
Execute if block
False
Execute else block
Continue with rest of program
Flowchart Implementation Example
# Implementing the if-else flowchart in Python
print("=== Traffic Light System ===")
light_color = "yellow"  # Try "red", "green", "yellow"

if light_color == "red":
    print("🚦 Red Light: STOP!")
    action = "Stop your vehicle completely"
elif light_color == "yellow":
    print("🚦 Yellow Light: SLOW DOWN!")
    action = "Prepare to stop, slow down if safe"
elif light_color == "green":
    print("🚦 Green Light: GO!")
    action = "Proceed with caution"
else:
    print("⚠️ Invalid light color!")
    action = "Proceed with extreme caution"

print(f"Action: {action}")
print("Program continues after conditional...")

Comparison and Best Practices

Different types of conditional statements are suitable for different scenarios. Here's a comparison to help you choose the right one.

Type Best For When to Use Complexity Readability
Simple if Single condition check When you need to execute or skip a block Low High
if-else Two alternative paths Either-or decisions, pass/fail scenarios Low High
elif Ladder Multiple exclusive conditions When you have 3+ mutually exclusive options Medium Medium
Nested if Hierarchical conditions Multi-stage validation, complex logic High Low (if deeply nested)
Best Practices:
  • Use meaningful condition names for better readability
  • Avoid deeply nested if statements (more than 2-3 levels)
  • Use logical operators (and, or) to combine simple conditions
  • Always include a final else clause for handling unexpected cases
  • Use comments to explain complex conditional logic

Real-World Applications

Conditional statements are used everywhere in programming. Here are some practical applications:

E-commerce Discount System

Apply discounts based on order amount and user type:

if user_type == "premium":
    discount = 20
elif order_amount > 1000:
    discount = 15
elif order_amount > 500:
    discount = 10
else:
    discount = 5
Health Monitoring System

Check health metrics and provide recommendations:

if blood_pressure > 140:
    status = "High BP - Consult doctor"
elif blood_pressure < 90:
    status = "Low BP - Rest and hydrate"
else:
    status = "Normal - Keep monitoring"
Game AI Decision Making

AI character decisions based on game state:

if player_nearby:
    if player_health < 30:
        action = "attack"
    else:
        if ai_health > 70:
            action = "attack"
        else:
            action = "retreat"
else:
    action = "patrol"
Smart Home Automation

Control home devices based on conditions:

if time.hour > 18:
    if motion_detected:
        lights.on()
    else:
        lights.off()
elif temperature > 25:
    ac.on()
else:
    ac.off()

Practice Exercises

Try these exercises to test your understanding of Python conditional statements.

Conditional Statements Practice Script
# Python Conditional Statements Practice Exercises

print("=== Exercise 1: Traffic Light System ===")
# Write a program that takes a light color as input
# and tells the user what to do
# Red: Stop, Yellow: Slow down, Green: Go, Other: Invalid color
light_color = "red"  # Try different values

if light_color == "red":
    print("🛑 STOP!")
elif light_color == "yellow":
    print("⚠️ SLOW DOWN!")
elif light_color == "green":
    print("✅ GO!")
else:
    print("❓ Invalid light color!")

print("\n=== Exercise 2: BMI Calculator ===")
# Calculate BMI = weight(kg) / (height(m) ** 2)
weight = 70
height = 1.75
bmi = weight / (height ** 2)

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25:
    category = "Normal"
elif bmi < 30:
    category = "Overweight"
else:
    category = "Obese"

print(f"Weight: {weight}kg, Height: {height}m")
print(f"BMI: {bmi:.1f}")
print(f"Category: {category}")

print("\n=== Exercise 3: Leap Year Checker ===")
year = 2024
# A year is a leap year if:
# 1. Divisible by 400, OR
# 2. Divisible by 4 but NOT divisible by 100
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")

print("\n=== Exercise 4: Simple Calculator ===")
num1 = 10
num2 = 5
operation = "/"  # Try +, -, *, /

if operation == "+":
    result = num1 + num2
    print(f"{num1} + {num2} = {result}")
elif operation == "-":
    result = num1 - num2
    print(f"{num1} - {num2} = {result}")
elif operation == "*":
    result = num1 * num2
    print(f"{num1} * {num2} = {result}")
elif operation == "/":
    if num2 != 0:
        result = num1 / num2
        print(f"{num1} / {num2} = {result}")
    else:
        print("Error: Division by zero!")
else:
    print("Invalid operation!")

print("\n=== Exercise 5: Password Strength Checker ===")
password = "Secure@123"
length_ok = len(password) >= 8
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(not c.isalnum() for c in password)

criteria_met = sum([has_upper, has_lower, has_digit, has_special])

if length_ok and criteria_met == 4:
    strength = "Strong"
elif length_ok and criteria_met >= 3:
    strength = "Medium"
else:
    strength = "Weak"

print(f"Password: {password}")
print(f"Strength: {strength}")

Key Takeaways

  • Simple if: Executes code only when condition is True
  • if-else: Provides two alternative execution paths
  • elif ladder: Handles multiple exclusive conditions sequentially
  • Nested if: Places if statements inside other if statements for complex logic
  • Python uses indentation (4 spaces) to define code blocks - this is mandatory
  • Conditions are Boolean expressions that evaluate to True or False
  • Use and, or, not operators to combine conditions
  • In elif ladders, order matters - conditions are checked top to bottom
  • Avoid deep nesting (more than 2-3 levels) for better readability
  • Always include an else clause for handling unexpected cases
  • Use flowcharts to visualize complex decision logic