Programming with Python | Chapter 4: Control Flow – Conditional Statements (if/elif/else)

Chapter Objectives

  • Understand the concept of control flow in programming.
  • Learn how to use comparison operators to compare values.
  • Understand and apply logical operators (and, or, not) to combine conditions.
  • Implement decision-making using if, elif, and else statements.
  • Understand the importance of indentation in Python’s control structures.
  • Write nested conditional statements.
  • Recognize the boolean context of conditions.

Introduction

So far, our programs have executed instructions sequentially, one after another from top to bottom. However, most real-world programs need to make decisions and execute different code blocks based on whether certain conditions are met. This chapter introduces control flow, specifically conditional statements. We will learn how to use comparison operators to create conditions (expressions that evaluate to True or False) and logical operators to combine multiple conditions. The core of this chapter focuses on the if, elif (else if), and else statements, which allow your program to follow different paths of execution based on these conditions.

Theory & Explanation

Control Flow

Control flow refers to the order in which statements are executed in a program. By default, it’s sequential. Conditional statements and loops (covered later) allow us to alter this default flow, enabling programs to react dynamically to different inputs and situations.

Comparison Operators

Comparison operators are used to compare two values. The result of a comparison is always a Boolean value (True or False).

Operator Name Description Example (a=10, b=5) Result
== Equal to Checks if the values of two operands are equal a == b * 2 True
!= Not equal to Checks if the values of two operands are not equal a != b True
> Greater than Checks if the left operand is greater than the right a > b True
< Less than Checks if the left operand is less than the right a < b False
>= Greater than or equal Checks if the left operand is greater than or equal to the right a >= 10 True
<= Less than or equal Checks if the left operand is less than or equal to the right b <= 5 True

Important: Note the difference between the assignment operator (=) which assigns a value, and the equality comparison operator (==) which checks if two values are equal.

Python
x = 5    # Assignment: x now holds the value 5
print(x == 5) # Comparison: Checks if x is equal to 5 -> True
print(x == 7) # Comparison: Checks if x is equal to 7 -> False
print(x > 2)  # Comparison: Checks if x is greater than 2 -> True

Logical Operators

Logical operators are used to combine multiple boolean expressions (conditions).

Operator Description Example (x=True, y=False) Result
and Returns True if both operands are true x and y False
or Returns True if at least one of the operands is true x or y True
not Reverses the logical state of its operand not y True

Truth Tables:

and Operator

A B A and B
True True True
True False False
False True False
False False False

True only when both conditions are True

or Operator

A B A or B
True True True
True False True
False True True
False False False

True when at least one condition is True

not Operator

A not A
True False
False True

Reverses the logical state

Python
age = 25
has_ticket = True
is_vip = False

# Example using 'and'
can_enter_concert = age >= 18 and has_ticket
print(f"Can enter concert? {can_enter_concert}") # True (both conditions are True)

# Example using 'or'
can_access_lounge = is_vip or age > 65
print(f"Can access lounge? {can_access_lounge}") # False (both conditions are False)

# Example using 'not'
is_minor = not (age >= 18)
print(f"Is minor? {is_minor}") # False (age >= 18 is True, so not True is False)

The if Statement

The if statement executes a block of code only if a specified condition evaluates to True.

Syntax:

Python
if condition:
    # Code block to execute if condition is True
    # This block MUST be indented
    statement1
    statement2
# Code here is executed regardless (it's outside the if block)

Indentation is Crucial: Python uses indentation (typically 4 spaces) to define code blocks. All lines belonging to the if block must be indented at the same level. The block ends when the indentation returns to the previous level.

graph TD
    A[Start] --> B{Condition?};
    B -- True --> C[Execute Indented Block];
    B -- False --> D[Continue after if];
    C --> D;

The if-else Statement

The if-else statement provides an alternative block of code to execute if the if condition evaluates to False.

Syntax:

Python
if condition:
    # Code block if condition is True (indented)
    statement_if_true
else:
    # Code block if condition is False (indented)
    statement_if_false
# Code here executes after either the 'if' or 'else' block

graph TD
    A[Start] --> B{Condition?};
    B -- True --> C[Execute 'if' Block];
    B -- False --> D[Execute 'else' Block];
    C --> E[Continue after if-else];
    D --> E;

The if-elif-else Statement

When you need to check multiple conditions sequentially, use the if-elif-else structure. elif stands for “else if”. Python checks the conditions one by one:

  1. It checks the if condition. If True, its block executes, and the rest of the elif/else chain is skipped.
  2. If the if condition is False, it checks the first elif condition. If True, its block executes, and the rest is skipped.
  3. This continues for any subsequent elif conditions.
  4. If all if and elif conditions are False, the else block (if present) executes.

Syntax:

Python
if condition1:
    # Block for condition1 True
    statement1
elif condition2:
    # Block for condition1 False AND condition2 True
    statement2
elif condition3:
    # Block for condition1 False AND condition2 False AND condition3 True
    statement3
# ... more elif blocks if needed
else:
    # Optional block if ALL preceding conditions are False
    statement_else
# Code here executes after the entire if-elif-else chain

graph TD
    A[Start] --> B{Condition 1?}
    B -- True --> C[Execute Block 1]
    B -- False --> D{Condition 2?}
    D -- True --> E[Execute Block 2]
    D -- False --> F{Condition 3?}
    F -- True --> G[Execute Block 3]
    F -- False --> H["Execute 'else' Block (Optional)"]
    C --> Z[Continue after chain]
    E --> Z
    G --> Z
    H --> Z

Nested Conditionals

You can place if, elif, or else statements inside the code blocks of other conditional statements. This is called nesting. Be mindful of indentation, as it determines which block the nested statement belongs to. Excessive nesting can make code hard to read.

Python
score = 85
attendance = 95

if score >= 60:
    print("Passed the base requirement.")
    if attendance >= 90:
        print("Eligible for distinction due to high attendance.")
    else:
        print("Good score, but attendance too low for distinction.")
else:
    print("Failed the base requirement.")
    if attendance < 50:
        print("Attendance critically low.")

Boolean Context (“Truthiness”)

In Python, conditions don’t strictly need to evaluate to True or False. Python considers certain values “truthy” (evaluate to True in a boolean context) and others “falsy” (evaluate to False).

Category Examples Evaluates to (in boolean context)
Falsy False, None, 0, 0.0, "", [], {}, () False
Truthy True, 1, -10, "Hello", [1, 2], {'a': 1}, any non-empty object True
  • Falsy Values: False, None, 0, 0.0, "" (empty string), [] (empty list), {} (empty dictionary), () (empty tuple), empty sets.
  • Truthy Values: Everything else, including non-zero numbers, non-empty strings/collections, and True.
Python
my_list = []
if my_list: # Checks if my_list is truthy (it's falsy because it's empty)
    print("List has items.")
else:
    print("List is empty.") # This will be printed

name = "Alice"
if name: # Checks if name is truthy (it's truthy because it's non-empty)
    print(f"Name found: {name}") # This will be printed

Code Examples

Check this LAB out for Interactive demo

Example 1: Simple if-else

Python
# age_check.py

age_str = input("Please enter your age: ")
age = int(age_str) # Convert input string to integer

if age >= 18:
    print("You are considered an adult.")
else:
    print("You are considered a minor.")

print("Age check complete.") # This line always executes

Explanation:

  • The program gets the user’s age and converts it to an integer.
  • The if statement checks if age is greater than or equal to 18.
  • If True, the first print statement executes.
  • If False, the else block executes, printing the second message.
  • The final print statement is outside the if-else block, so it runs regardless of the age.

Example 2: if-elif-else for Grading

Python
# grading.py

score_str = input("Enter the test score (0-100): ")
score = int(score_str)

grade = "" # Initialize grade variable

if score >= 90:
    grade = "A"
elif score >= 80: # Only checked if score < 90
    grade = "B"
elif score >= 70: # Only checked if score < 80
    grade = "C"
elif score >= 60: # Only checked if score < 70
    grade = "D"
else: # Only executed if score < 60
    grade = "F"

print(f"The score {score} corresponds to grade: {grade}")

Explanation:

  • The code gets a score and converts it to an integer.
  • It checks conditions sequentially:
    • Is score >= 90? If yes, grade = "A", and the rest is skipped.
    • If no, is score >= 80? If yes, grade = "B", and the rest is skipped.
    • …and so on.
  • The else block catches any score below 60.
  • Finally, the calculated grade is printed.

Example 3: Combining Conditions with Logical Operators

Python
# login_check.py

username = input("Enter username: ")
password = input("Enter password: ")

is_admin = False # Flag to check if user is admin

# Check for regular user login OR admin login
if (username == "user1" and password == "pass123") or \
   (username == "admin" and password == "admin@123"):
    print("Login successful!")
    if username == "admin": # Nested if to check if the logged-in user is admin
        is_admin = True
else:
    print("Login failed. Incorrect username or password.")

# Further action based on admin status
if is_admin:
    print("Admin privileges granted.")
else:
    print("Standard user access.")

Explanation:

  • The if condition uses and to check specific username/password pairs and or to allow login if either pair matches. The backslash \ is used to continue the long line.
  • A nested if checks if the successful login was by the “admin”.
  • An else block handles failed login attempts.
  • A separate if statement later uses the is_admin boolean flag (set within the nested if) to determine privileges.

Common Mistakes or Pitfalls

  • = vs ==: Using the assignment operator (=) instead of the comparison operator (==) inside an if condition. This is a syntax error in modern Python but a common logical error in other languages. Python helps prevent this.
  • Indentation Errors: Inconsistent or incorrect indentation. All lines within a specific block (if, elif, else) must have the same indentation level.
  • Missing Colon: Forgetting the colon (:) at the end of the if, elif, or else line.
  • Order of elif: The order matters in if-elif-else chains. More specific conditions should often come before more general ones if there’s overlap.
  • Overly Complex Nesting: Deeply nested if statements can be hard to read and debug. Consider refactoring using functions or simplifying the logic.
  • Boolean Logic Errors: Mistakes in combining conditions with and/or/not, especially regarding operator precedence (not binds tightest, then and, then or). Use parentheses () to clarify or enforce order when unsure.

Chapter Summary

  • Control flow dictates the execution order of statements.
  • Comparison operators (==, !=, >, <, >=, <=) compare values and result in True or False.
  • Logical operators (and, or, not) combine boolean conditions.
  • The if statement executes a block if its condition is True.
  • The if-else statement provides an alternative block for when the if condition is False.
  • The if-elif-else chain checks multiple conditions sequentially, executing the block of the first True condition found.
  • Indentation (usually 4 spaces) defines code blocks in Python and is mandatory for control structures.
  • Nesting allows placing conditional statements inside others.
  • Values in Python have a boolean context (“truthiness” or “falsiness”) allowing non-boolean values to be used directly in conditions.

Exercises & Mini Projects

Exercises

  1. Even or Odd Revisited: Ask the user for an integer. Use an if-else statement to print whether the number is “Even” or “Odd”. (Hint: Use the modulo operator %).
  2. Number Comparison: Ask the user for two numbers. Compare them and print one of the following messages: “First number is greater”, “Second number is greater”, or “Numbers are equal”. Use an if-elif-else structure.
  3. Age Group Classifier: Ask the user for their age. Use if-elif-else to classify them into one of these groups and print the result:
    • 0-12: Child
    • 13-19: Teenager
    • 20-64: Adult
    • 65+: Senior
  4. Leap Year Check: Ask the user for a year. Determine if it’s a leap year and print the result. A year is a leap year if:
    • It is divisible by 4, unless…
    • It is also divisible by 100, unless…
    • It is also divisible by 400.(Hint: Use nested if statements or combine conditions with and, or, not).
  5. Username Validation (Enhanced): Ask the user for a username. Check the following conditions using if/elif/else and logical operators:
    • If the username is empty, print “Username cannot be empty.”
    • Else if the username contains spaces, print “Username cannot contain spaces.” (Use find() or in).
    • Else if the length of the username is less than 4 characters, print “Username too short (minimum 4 characters).”
    • Else, print “Username is valid.”

if-elif-else Grading Demo

0 50 100
Current Score: 75

if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"

Mini Project: Simple Calculator

Goal: Create a script calculator.py that performs basic arithmetic operations based on user input.

Steps:

  1. Ask the user to enter the first number (num1). Convert it to a float.
  2. Ask the user to enter the desired operation (+, -, *, /). Store it as a string.
  3. Ask the user to enter the second number (num2). Convert it to a float.
  4. Use an if-elif-else structure to check the value of the operation variable:
    • If operation is "+": Calculate result = num1 + num2.
    • If operation is "-": Calculate result = num1 - num2.
    • If operation is "*": Calculate result = num1 * num2.
    • If operation is "/":
      • Add a nested if check: If num2 is 0 or 0.0, print an error message “Error: Cannot divide by zero.” and perhaps set result to None or skip printing.
      • Else (if num2 is not zero), calculate result = num1 / num2.
    • Else (if the operation symbol is none of the above): Print an error message “Invalid operation symbol.” and set result to None or skip printing.
  5. If a valid result was calculated (i.e., not an error case), print the result using an f-string, for example: f"{num1} {operation} {num2} = {result}".

Additional Sources:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top