Unit II: Control Structures
Table of Contents
1. Introduction to Control Structures
2. Selective Statements
– if Statement
– if-else Statement
– Nested if Statements
– if-elif Ladder Statements
3. Iterative Statements
– while Loop
– for Loop
– Nested Loops
– else in Loops
4. Control Flow Manipulation
– break Statement
– continue Statement
– pass Statement
5. Practice Problems
6. Summary
Introduction to Control Structures
Control structures are fundamental programming constructs that allow you to control the
flow of execution in your Python programs. Without control structures, programs would
execute linearly, statement by statement, in the exact order they're written. Control
structures give programs the ability to:
Make decisions
Execute code conditionally
Repeat operations
Skip certain operations
Respond dynamically to different inputs and states.
Types of Control Structures in Python
Python provides two main categories of control structures:
1. Selective Statements (Decision-Making)
2. Iterative Statements(Loops)
Selective Statements
Selective statements allow a program to execute different code blocks based on whether
certain conditions are true or false. Python uses Boolean expressions that evaluate to True
or False to determine which code path to follow. Main types include:
if statements
if-else statements
Nested if statements
if-elif-else ladder statements.
if Statement:
The if statement is the most basic form of conditional execution. It executes a block of
code only if a specified condition evaluates to True.
Syntax:
if condition:
# Code block to execute if condition is True
Key points: - The condition is a Boolean expression that evaluates to either True or False
- The indented block of code under the if statement is executed only if the condition is
True - Python uses indentation (typically 4 spaces) to define blocks of code, not braces {}
as in many other languages - The colon : is mandatory after the condition
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
print("Please register if you haven't already.")
print("This will print regardless of the condition.")
Output:
You are eligible to vote.
Please register if you haven't already.
This will print regardless of the condition.
if-else Statement:
The if-else statement extends the basic if statement by providing an alternative block
of code to execute when the condition is False.
Syntax:
if condition:
# Code block to execute if condition is True
else:
# Code block to execute if condition is False
Key points: - Only one of the two code blocks will execute, never both - The else block is
optional but provides a way to handle all cases where the condition is False - Both blocks
must be properly indented
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
print("You need to wait", 18 - age, "more years.")
Output:
You are not eligible to vote yet.
You need to wait 2 more years.
Nested if Statements:
A nested if statement is an if statement inside another if or else block. This allows for
more complex conditions and decision-making processes.
Syntax:
if outer_condition:
# Code to execute if outer_condition is True
if inner_condition:
# Code to execute if both outer_condition and inner_condition
are True
else:
# Code to execute if outer_condition is True but
inner_condition is False
else:
# Code to execute if outer_condition is False
Key points: - Nesting can be multiple levels deep, but excessive nesting can make code
difficult to read and maintain - Each level of nesting requires proper indentation - Use
nested if statements when you need to check multiple conditions sequentially
Example:
age = 20
has_id = True
if age >= 18:
print("Age requirement met.")
if has_id:
print("You can enter the venue.")
else:
print("You need to show a valid ID.")
else:
print("You must be 18 or older to enter.")
Output:
Age requirement met.
You can enter the venue.
if-elif Ladder Statements
The if-elif-else ladder (or chain) allows testing of multiple conditions in sequence,
executing the block of code associated with the first condition that evaluates to True.
Syntax:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
elif condition3:
# Code to execute if condition1 and condition2 are False and
condition3 is True
...
else:
# Code to execute if all conditions are False
Key points: - The conditions are tested in order from top to bottom - Only the code block
associated with the first true condition is executed - The else block is optional and acts as
a default case when all conditions are False - The elif is short for “else if” and can be
used multiple times in a ladder - Each condition is only evaluated if all previous conditions
were False
Flow chart for if-elif-else ladder:
Example:
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
Iterative Statements
Iterative statements, or loops, allow a program to execute a block of code repeatedly as
long as a condition is met or for a specified number of iterations.
while Loop
The while loop executes a block of code as long as a specified condition remains True.
Syntax:
while condition:
# Code block to execute repeatedly while condition is True
Key points: - The condition is evaluated before each iteration - If the condition is initially
False, the loop body will never execute - The loop continues until the condition becomes
False - It’s important to ensure that the condition will eventually become False to avoid
infinite loops - Variables used in the condition often need to be updated within the loop
body
Example:
count = 1
while count <= 5:
print(f"Count is: {count}")
count += 1 # Increment count to avoid infinite loop
print("Loop finished!")
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Loop finished!
Infinite loop example (avoid this):
# WARNING: This will run forever!
# while True:
# print("This will never end!")
Example: Validating user input:
valid_input = False
while not valid_input:
user_input = input("Enter a number between 1 and 10: ")
if user_input.isdigit():
num = int(user_input)
if 1 <= num <= 10:
valid_input = True
print(f"Thank you! You entered: {num}")
else:
print("Number must be between 1 and 10.")
else:
print("Please enter a valid number.")
for Loop
The for loop in Python is designed to iterate over items of a sequence (like a list, tuple,
dictionary, set, or string) or any iterable object.
Syntax:
for variable in iterable:
# Code block to execute for each item in the iterable
Key points: - The loop variable takes the value of each item in the iterable one by one - The
loop automatically terminates when all items in the iterable have been processed - The
range() function is commonly used to generate a sequence of numbers for the loop
Example with a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}s")
Output:
I like apples
I like bananas
I like cherrys
Example with range():
# range(5) generates numbers from 0 to 4
for i in range(5):
print(f"Number: {i}")
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
range() function variations: - range(stop): Generates numbers from 0 to stop-1 -
range(start, stop): Generates numbers from start to stop-1 - range(start, stop,
step): Generates numbers from start to stop-1 with the given step
Example with range variations:
# range(1, 6): numbers from 1 to 5
print("range(1, 6):")
for i in range(1, 6):
print(i, end=" ")
print("\n")
# range(2, 11, 2): even numbers from 2 to 10
print("range(2, 11, 2):")
for i in range(2, 11, 2):
print(i, end=" ")
print("\n")
# range(10, 0, -1): countdown from 10 to 1
print("range(10, 0, -1):")
for i in range(10, 0, -1):
print(i, end=" ")
Output:
range(1, 6):
1 2 3 4 5
range(2, 11, 2):
2 4 6 8 10
range(10, 0, -1):
10 9 8 7 6 5 4 3 2 1
Looping through strings:
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Looping through dictionaries:
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Iterate through keys
print("Keys:")
for key in student:
print(key)
# Iterate through values
print("\nValues:")
for value in [Link]():
print(value)
# Iterate through key-value pairs
print("\nKey-value pairs:")
for key, value in [Link]():
print(f"{key}: {value}")
Output:
Keys:
name
age
major
Values:
Alice
21
Computer Science
Key-value pairs:
name: Alice
age: 21
major: Computer Science
Nested Loops
Nested loops are loops inside other loops. The inner loop executes completely for each
iteration of the outer loop.
Syntax:
for outer_var in outer_iterable:
# Outer loop code
for inner_var in inner_iterable:
# Inner loop code
Key points: - For each iteration of the outer loop, the inner loop executes completely - Can
be used for working with multi-dimensional data structures, like matrices - Be cautious
with deeply nested loops as they can lead to performance issues - Any combination of for
and while loops can be nested
Example: Multiplication table:
for i in range(1, 4): # Outer loop: 1 to 3
for j in range(1, 4): # Inner loop: 1 to 3
product = i * j
print(f"{i} × {j} = {product}", end="\t")
print() # New line after each row
Output:
1 × 1 = 1 1 × 2 = 2 1 × 3 = 3
2 × 1 = 2 2 × 2 = 4 2 × 3 = 6
3 × 1 = 3 3 × 2 = 6 3 × 3 = 9
Example: Pattern printing:
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end=" ")
print() # Move to the next line
Output:
*
* *
* * *
* * * *
* * * * *
Example: Iterating through a 2D list (matrix):
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Matrix elements:")
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each row
print("\nMatrix with indices:")
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f"matrix[{i}][{j}] = {matrix[i][j]}")
Output:
Matrix elements:
1 2 3
4 5 6
7 8 9
Matrix with indices:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
matrix[2][0] = 7
matrix[2][1] = 8
matrix[2][2] = 9
else in Loops
Python allows an else clause with both for and while loops. The else block executes
after the loop completes normally (without being terminated by a break statement).
Syntax:
for item in iterable:
# Loop body
else:
# Code to execute after loop completes normally
# Or for while loops:
while condition:
# Loop body
else:
# Code to execute after loop completes normally
Key points: - The else block executes only if the loop completes all its iterations without
encountering a break - If a break statement terminates the loop, the else block is skipped
- This feature is unique to Python and not found in many other programming languages -
Useful for implementing search algorithms and validation scenarios
Example with for loop:
numbers = [1, 3, 5, 7, 9]
search_for = 4
for num in numbers:
if num == search_for:
print(f"Found {search_for}!")
break
else:
print(f"{search_for} not found in the list.")
Output:
4 not found in the list.
Example with while loop:
attempts = 0
max_attempts = 3
correct_password = "python123"
while attempts < max_attempts:
password = input("Enter password: ")
attempts += 1
if password == correct_password:
print("Access granted!")
break
print(f"Incorrect password. {max_attempts - attempts} attempts
remaining.")
else:
print("Access denied after multiple failed attempts.")
Output (sample):
Enter password: wrong1
Incorrect password. 2 attempts remaining.
Enter password: wrong2
Incorrect password. 1 attempts remaining.
Enter password: wrong3
Incorrect password. 0 attempts remaining.
Access denied after multiple failed attempts.
Control Flow Manipulation
Python provides several statements to manipulate the flow of control within loops and
conditional statements.
break Statement
The break statement immediately terminates the current loop and transfers control to the
statement following the loop.
Syntax:
while condition:
# Loop code
if break_condition:
break # Exit the loop
# Or in for loops:
for item in iterable:
# Loop code
if break_condition:
break # Exit the loop
Key points: - When encountered, break immediately stops the execution of the current
loop - In nested loops, break only exits the innermost loop that contains it - Often used to
exit loops when a specific condition is met, like finding a target value - Can be used to
implement early termination for efficiency
Example: Finding a number in a list:
numbers = [10, 20, 30, 40, 50]
target = 30
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
break # Stop searching once found
print(f"Checked index {i}")
Output:
Checked index 0
Checked index 1
Found 30 at index 2
Example: Exiting when invalid input is provided:
while True:
user_input = input("Enter a positive number (or 'q' to quit): ")
if user_input.lower() == 'q':
print("Exiting program.")
break
try:
number = float(user_input)
if number <= 0:
print("Please enter a positive number.")
else:
print(f"Square root of {number} is {number ** 0.5:.4f}")
except ValueError:
print("Invalid input. Please enter a number or 'q'.")
continue Statement
The continue statement skips the rest of the current iteration and jumps to the next
iteration of the loop.
Syntax:
while condition:
# Loop code
if skip_condition:
continue # Skip to the next iteration
# More code (skipped if continue is executed)
# Or in for loops:
for item in iterable:
# Loop code
if skip_condition:
continue # Skip to the next iteration
# More code (skipped if continue is executed)
Key points: - When encountered, continue skips the remaining code in the current
iteration - The loop then proceeds with the next iteration - Useful for filtering or skipping
certain values in a collection - Can improve readability by reducing the level of nesting
Example: Processing only even numbers:
for num in range(1, 11):
if num % 2 != 0: # If number is odd
continue # Skip to the next number
print(f"{num} is even")
Output:
2 is even
4 is even
6 is even
8 is even
10 is even
Example: Filtering user input:
valid_numbers = []
print("Enter 5 positive integers:")
count = 0
while count < 5:
user_input = input(f"Enter number {count+1}: ")
# Skip invalid inputs
if not user_input.isdigit() or int(user_input) <= 0:
print("Please enter a positive integer.")
continue
number = int(user_input)
valid_numbers.append(number)
count += 1
print("Valid numbers:", valid_numbers)
pass Statement
The pass statement is a null operation; it does nothing. It is used as a placeholder where
syntax requires a statement but no action is needed.
Syntax:
if condition:
pass # Do nothing
# Or in loops:
for item in iterable:
pass
# Or in function definitions:
def function_name():
pass
Key points: - pass is syntactically needed but performs no action - Used as a placeholder
during development when the implementation is not yet complete - Helpful for creating
minimal classes or functions that will be implemented later - Can be used to create empty
blocks in control structures
Example: Placeholder for future implementation:
def calculate_tax(income):
# TODO: Implement tax calculation
pass
def process_data(data):
if not data:
pass # Handle empty data later
else:
# Process the data
result = data
return result
# Empty class definition
class Customer:
pass # Will add attributes and methods later
Example: Using pass in a loop:
# Find the first even number, but don't do anything with it
for num in range(1, 10):
if num % 2 == 0:
pass # Found an even number, but taking no action
Practice Problems
Problem 1: FizzBuzz
Write a program that prints numbers from 1 to 100. But for multiples of 3, print “Fizz”
instead of the number, and for multiples of 5, print “Buzz”. For numbers that are multiples
of both 3 and 5, print “FizzBuzz”.
# Solution
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Problem 2: Prime Number Checker
Write a function to check if a number is prime.
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Test the function
for num in range(1, 21):
if is_prime(num):
print(f"{num} is prime")
else:
print(f"{num} is not prime")
Problem 3: Pattern Printing
Write a program to print a pyramid pattern.
rows = 5
for i in range(1, rows + 1):
# Print spaces
for j in range(rows - i):
print(" ", end="")
# Print stars
for k in range(2 * i - 1):
print("*", end="")
print() # Move to next line
Output:
*
***
*****
*******
*********
Summary
In this unit, we covered:
1. Selective Statements:
– if statement for basic conditional execution
– if-else for binary decisions
– Nested if statements for complex conditions
– if-elif-else ladder for multiple conditions
2. Iterative Statements:
– while loop for condition-based iteration
– for loop for sequence iteration
– Nested loops for working with multi-dimensional data
– else clause with loops for handling normal loop completion
3. Control Flow Manipulation:
– break to exit a loop immediately
– continue to skip the current iteration
– pass as a placeholder for future implementation
Understanding these control structures is fundamental to writing efficient and effective
Python programs. These constructs allow you to create programs that can make decisions,
repeat actions, and respond dynamically to different inputs and conditions.
Key Takeaways: - Python uses indentation to define code blocks, not braces {} - The colon
: is required at the end of control structure headers - Boolean expressions evaluate to True
or False and determine execution paths - Nested structures allow for complex decision-
making and data processing - break, continue, and pass provide fine-grained control
over execution flow - The else clause in loops is a unique Python feature for handling
normal loop completion