Python Control Flow: if, else, elif

This tutorial introduces Python's control flow statements—if, else, elif, and nested conditions. These constructs allow your program to make decisions based on conditions, enabling dynamic and responsive code.

What is Control Flow?

Control flow determines the order in which a program's statements are executed. Python uses conditional statements (if, else, elif) to execute code blocks based on whether certain conditions are true or false. This allows programs to respond to different inputs or states dynamically.

Why Use Control Flow?

Without control flow, every instruction in your program would run unconditionally. Control statements allow you to:

  • Execute code only when a condition is true
  • Choose between multiple actions
  • Handle complex decision-making in your program

The if Statement

The if statement evaluates a condition (an expression that returns True or False). If the condition is True, the code block inside the if is executed.

Syntax:

if condition:
    # code block to run if condition is true

Example

age = 20
if age >= 18:
    print("You are eligible to vote.")

Explanation:

  • If the condition age >= 18 evaluates to True, the indented code block runs.
  • If the condition is False, Python skips the block.

The if...else Statement

The else statement provides an alternative code block to execute when the if condition is False.

Syntax

if condition:
    # code if condition is true
else:
    # code if condition is false

Example

temperature = 25
if temperature > 30:
    print("It's a hot day.")
else:
    print("The weather is pleasant.")

Explanation:

  • A variable temperature is initialized with the value 25.
  • The program checks if the value of temperature is greater than 30 (which is not in this case.)
  • If the condition temperature > 30 is False (which it is, since 25 is not greater than 30), the else block is executed instead.

The output will be:

The weather is pleasant.

This example shows how you can control the flow of your program based on different conditions using if and else.

The if...elif...else Statement

When you have multiple conditions to evaluate, use elif (short for "else if").

Syntax:

if condition1:
    # code block 1
elif condition2:
    # code block 2
elif condition3:
    # code block 3
else:
    # code block if all conditions are false

Example:

marks = 85
if marks >= 90:
    print("Grade: A")
elif marks >= 80:
    print("Grade: B")
elif marks >= 70:
    print("Grade: C")
else:
    print("Grade: D")

Output:

Grade: B

Nested if Statements

You can place one if (or if-else) statement inside another to handle more complex logic. Nested if statements allow multiple levels of decision-making.

x = 15
if x > 10:
    if x < 20:
        print("x is between 10 and 20")
    else:
        print("x is 20 or more")
else:
    print("x is 10 or less")

Explanation:

  • A variable x is assigned the value 15.
  • Checks if x is greater than 10.
  • Since x = 15, this condition is True, so Python enters the first if block.
  • Now the code checks if x is less than 20.
  • Since x = 15, this condition is also True, so it prints:
x is between 10 and 20

Practical Use Cases of if...elif...else

Check if a number is positive, negative, or zero

num = 0
if num > 0:
    print("Positive number")
elif num < 0:
    print("Negative number")
else:
    print("Zero")

The output is:

Zero

Check if a number is even or odd

number = 11
if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

The output is:

Odd number

Login validation

username = "admin"
password = "1234"
if username == "admin":
    if password == "1234":
        print("Login successful")
    else:
        print("Incorrect password")
else:
    print("Invalid username")

The output is;

Login successful

Age group classification

age = 45
if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
elif age < 60:
    print("Adult")
else:
    print("Senior")

The output is:

Adult

Logical Operators in Conditions

Here are some simple examples demonstrating how to use logical operators (and, or, not) in Python if statements:

# AND example
x = 5
if x > 0 and x < 10:
    print("x is between 0 and 10")
# OR example
y = -3
if y < 0 or y > 100:
    print("y is either negative or very large")
# NOT example
z = False
if not z:
    print("z is False")

The following is a more detailed example of if condition with logical operators.

# Example: Movie Ticket Eligibility Checker
# You can change the values of the variables to see different results
# variables
age = 12
has_ticket = 'yes'
is_weekend = False  
# Check eligibility using logical operators
if age >= 18 and has_ticket:
    print("You can watch an R-rated movie alone.")
elif (age >= 13 or has_ticket) and not is_weekend:
    print("You can watch a PG-13 movie on weekdays.")
elif not has_ticket:
    print("Sorry, you need a ticket to enter.")
else:
    print("Sorry, you don't meet the requirements.")

Explanation:

  • Logical Operators Used:
    • and: Both conditions must be True
    • or: At least one condition must be True
    • not: Inverts the boolean value (True becomes False, False becomes True)
  • How the Code Works:
    • First we get user input for age and whether they have a ticket.
    • The first if checks if BOTH conditions are true (18+ AND has ticket)
    • The elif checks if EITHER age is 13+ OR they have a ticket, AND it's NOT weekend
    • The next elif checks if they DON'T have a ticket
    • The else catches all other cases
  • Truth Table Concept:
    • A and B is True only if both A and B are True
    • A or B is True if either A or B (or both) are True
    • not A is True if A is False, and vice versa

Common Mistakes to Avoid

Mistake Why it's wrong
Missing indentation Python uses indentation to define code blocks.
Using = instead of == = is for assignment, == is for comparison.
Forgetting colons : Required after if, elif, and else.

Best Practices

  • Use meaningful variable names
  • Keep conditionals readable
  • Use parentheses to clarify complex conditions (optional but helpful)
  • Don't over-nest if statements — consider using logical operators (and, or) instead

Mini Quiz

  • What does if x = 10: do?
  • What's the purpose of elif?
  • Can we use multiple elif blocks in one statement?
  • What happens if no condition in if/elif is True and there's no else?

Summary

  • if, else, and elif are used to make decisions in Python.
  • Use if to test conditions, else to define a fallback, and elif for multiple options.
  • Nested if statements handle complex decision trees.
  • Logical operators (and, or, not) help simplify compound conditions.