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
, andelse
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.

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).
Truth Tables:
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:
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:
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:
- It checks the
if
condition. IfTrue
, its block executes, and the rest of theelif
/else
chain is skipped. - If the
if
condition isFalse
, it checks the firstelif
condition. IfTrue
, its block executes, and the rest is skipped. - This continues for any subsequent
elif
conditions. - If all
if
andelif
conditions areFalse
, theelse
block (if present) executes.
Syntax:
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.
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
).
- 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
.
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
Example 1: Simple if-else
# 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 ifage
is greater than or equal to 18. - If
True
, the firstprint
statement executes. - If
False
, theelse
block executes, printing the second message. - The final
print
statement is outside theif-else
block, so it runs regardless of the age.
Example 2: if-elif-else
for Grading
# 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.
- Is
- The
else
block catches any score below 60. - Finally, the calculated grade is printed.
Example 3: Combining Conditions with Logical Operators
# 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 usesand
to check specific username/password pairs andor
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 theis_admin
boolean flag (set within the nestedif
) to determine privileges.
Common Mistakes or Pitfalls
=
vs==
: Using the assignment operator (=
) instead of the comparison operator (==
) inside anif
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 theif
,elif
, orelse
line. Order of elif:
The order matters inif-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, thenand
, thenor
). 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 inTrue
orFalse
. - Logical operators (
and
,or
,not
) combine boolean conditions. - The
if
statement executes a block if its condition isTrue
. - The
if-else
statement provides an alternative block for when theif
condition isFalse
. - The
if-elif-else
chain checks multiple conditions sequentially, executing the block of the firstTrue
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
- 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%
). - 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. - 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
- 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).
- 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()
orin
). - Else if the length of the username is less than 4 characters, print “Username too short (minimum 4 characters).”
- Else, print “Username is valid.”
Mini Project: Simple Calculator
Goal: Create a script calculator.py
that performs basic arithmetic operations based on user input.
Steps:
- Ask the user to enter the first number (
num1
). Convert it to afloat
. - Ask the user to enter the desired operation (
+
,-
,*
,/
). Store it as a string. - Ask the user to enter the second number (
num2
). Convert it to afloat
. - Use an
if-elif-else
structure to check the value of theoperation
variable:- If
operation
is"+"
: Calculateresult = num1 + num2
. - If
operation
is"-"
: Calculateresult = num1 - num2
. - If
operation
is"*"
: Calculateresult = num1 * num2
. - If
operation
is"/"
:- Add a nested
if
check: Ifnum2
is0
or0.0
, print an error message “Error: Cannot divide by zero.” and perhaps setresult
toNone
or skip printing. - Else (if
num2
is not zero), calculateresult = num1 / num2
.
- Add a nested
- Else (if the operation symbol is none of the above): Print an error message “Invalid operation symbol.” and set
result
toNone
or skip printing.
- If
- 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: