Unit II: Program Flow Control
Master conditional statements and loops in Python
Conditional Blocks
Conditional statements allow your program to make decisions based on certain conditions. Python uses if, elif, and else keywords to create conditional logic.
How Conditions Work
A condition is an expression that evaluates to either True or False. Based on this evaluation, different blocks of code are executed.
# Basic condition evaluation
print(5 > 3) # True
print(5 < 3) # False
print(5 == 5) # True
print(5 != 5) # False
# Conditions with variables
age = 18
print(age >= 18) # True
# Combining conditions
score = 85
print(score >= 60 and score <= 100) # True
if, else, and elif Statements
The if Statement
The if statement executes a block of code only if the condition is True.
# Simple if statement
age = 20
if age >= 18:
print("You are an adult")
print("You can vote!")
# The above prints only if age >= 18
temperature = 35
if temperature > 30:
print("It's a hot day!")
print("Stay hydrated!")
The if-else Statement
The else block executes when the if condition is False.
# if-else statement
age = 16
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# Another example
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
The if-elif-else Statement
Use elif (else if) to check multiple conditions.
# if-elif-else for multiple conditions
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}")
# Another example: Day of the week
day = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
else:
print("Invalid day")
Nested if Statements
# Nested if statements
age = 25
has_license = True
if age >= 18:
print("Age requirement met")
if has_license:
print("You can drive!")
else:
print("You need a license to drive")
else:
print("You are too young to drive")
# Login system example
username = "admin"
password = "secret123"
input_user = "admin"
input_pass = "secret123"
if input_user == username:
if input_pass == password:
print("Login successful!")
else:
print("Incorrect password")
else:
print("User not found")
Ternary Operator (Shorthand if-else)
# Ternary operator: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# One-liner for min/max
a, b = 10, 20
smaller = a if a < b else b
print(f"Smaller: {smaller}") # 10
# With function calls
def check_even(n):
return "Even" if n % 2 == 0 else "Odd"
print(check_even(7)) # Odd
print(check_even(10)) # Even
For Loops in Python
A for loop is used to iterate over a sequence (list, tuple, string, dictionary, or range).
Basic For Loop
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
# Iterating over a string
for char in "Python":
print(char)
# Output: P y t h o n (each on new line)
For Loop with Lists
# Processing list items
numbers = [1, 2, 3, 4, 5]
# Calculate sum
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # Sum: 15
# Create a new list with doubled values
doubled = []
for num in numbers:
doubled.append(num * 2)
print(doubled) # [2, 4, 6, 8, 10]
# Using enumerate() to get index
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
# Output:
# 0: red
# 1: green
# 2: blue
For Loop with Strings
# Count vowels in a string
text = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"Vowels count: {count}") # Vowels count: 3
# Reverse a string
original = "Python"
reversed_str = ""
for char in original:
reversed_str = char + reversed_str
print(reversed_str) # nohtyP
# Check for palindrome
word = "radar"
is_palindrome = True
for i in range(len(word) // 2):
if word[i] != word[-(i+1)]:
is_palindrome = False
break
print(f"'{word}' is palindrome: {is_palindrome}") # True
For Loop with Dictionaries
# Iterating over dictionaries
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
# Iterate over keys (default)
print("Keys:")
for key in student:
print(key)
# Iterate over values
print("\nValues:")
for value in student.values():
print(value)
# Iterate over key-value pairs
print("\nKey-Value pairs:")
for key, value in student.items():
print(f"{key}: {value}")
# Output:
# Keys:
# name
# age
# grade
#
# Values:
# Alice
# 20
# A
#
# Key-Value pairs:
# name: Alice
# age: 20
# grade: A
For Loop Using Ranges
The range() function generates a sequence of numbers, commonly used with for loops.
Range Syntax
range(stop)- 0 to stop-1range(start, stop)- start to stop-1range(start, stop, step)- start to stop-1 with step increment
# range(stop) - 0 to stop-1
print("range(5):")
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
print()
# range(start, stop) - start to stop-1
print("\nrange(2, 7):")
for i in range(2, 7):
print(i, end=" ") # 2 3 4 5 6
print()
# range(start, stop, step)
print("\nrange(0, 10, 2):")
for i in range(0, 10, 2):
print(i, end=" ") # 0 2 4 6 8
print()
# Negative step (counting backwards)
print("\nrange(10, 0, -1):")
for i in range(10, 0, -1):
print(i, end=" ") # 10 9 8 7 6 5 4 3 2 1
print()
# Converting range to list
numbers = list(range(1, 6))
print(f"\nList from range: {numbers}") # [1, 2, 3, 4, 5]
Practical Range Examples
# Print multiplication table
n = 5
print(f"Multiplication table of {n}:")
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
# Sum of first n natural numbers
n = 100
total = 0
for i in range(1, n + 1):
total += i
print(f"\nSum of first {n} numbers: {total}") # 5050
# Factorial calculation
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"\n{num}! = {factorial}") # 120
# Print a pattern
print("\nTriangle pattern:")
for i in range(1, 6):
print("*" * i)
# *
# **
# ***
# ****
# *****
# Access list by index
fruits = ["apple", "banana", "cherry", "date"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
While Loops in Python
A while loop executes a block of code as long as a condition is True.
Warning
Be careful with while loops! If the condition never becomes False, you'll create an infinite loop that runs forever.
Basic While Loop
# Basic while loop
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # Don't forget to increment!
print("Loop finished!")
# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
# Loop finished!
While Loop Examples
# Sum until a condition
total = 0
num = 1
while total < 100:
total += num
num += 1
print(f"Sum reached {total} after adding numbers up to {num - 1}")
# Countdown
print("\nCountdown:")
seconds = 5
while seconds > 0:
print(seconds)
seconds -= 1
print("Blast off! š")
# User input validation
password = ""
attempts = 3
while password != "secret" and attempts > 0:
password = input(f"Enter password ({attempts} attempts left): ")
attempts -= 1
if password == "secret":
print("Access granted!")
elif attempts == 0:
print("Too many attempts. Account locked!")
else:
print("Wrong password. Try again.")
While with else
# The else block runs when condition becomes False
# (but NOT when loop is broken with break)
count = 1
while count <= 3:
print(f"Count: {count}")
count += 1
else:
print("Loop completed normally!")
# Output:
# Count: 1
# Count: 2
# Count: 3
# Loop completed normally!
# Searching example
numbers = [1, 3, 5, 7, 9]
target = 5
index = 0
while index < len(numbers):
if numbers[index] == target:
print(f"Found {target} at index {index}")
break
index += 1
else:
print(f"{target} not found in list")
Loop Control: break, continue, pass, else
Python provides several ways to control the flow within loops.
The break Statement
Exits the loop immediately, skipping remaining iterations.
# break - exit loop immediately
print("Finding first even number:")
for num in [1, 3, 5, 4, 7, 8, 9]:
if num % 2 == 0:
print(f"Found even number: {num}")
break
print(f"Checking {num}...")
# Output:
# Checking 1...
# Checking 3...
# Checking 5...
# Found even number: 4
# Search in list
fruits = ["apple", "banana", "cherry", "date"]
search = "cherry"
for fruit in fruits:
if fruit == search:
print(f"Found '{search}'!")
break
else:
print(f"'{search}' not in list")
The continue Statement
Skips the current iteration and moves to the next one.
# continue - skip current iteration
print("Odd numbers from 1 to 10:")
for num in range(1, 11):
if num % 2 == 0:
continue # Skip even numbers
print(num, end=" ")
print() # 1 3 5 7 9
# Skip specific items
fruits = ["apple", "banana", "cherry", "date"]
print("\nFruits (excluding banana):")
for fruit in fruits:
if fruit == "banana":
continue
print(fruit)
# Process only valid data
data = [10, -5, 20, -3, 15, 0]
print("\nProcessing positive numbers:")
for value in data:
if value <= 0:
continue
print(f"Processing: {value}")
The pass Statement
Does nothing - used as a placeholder when syntax requires a statement.
# pass - placeholder that does nothing
# Empty loop (for later implementation)
for i in range(5):
pass # TODO: implement later
# Empty function
def future_function():
pass # Will implement later
# Empty class
class MyClass:
pass
# Conditional placeholder
x = 10
if x > 5:
pass # Handle this case later
else:
print("x is 5 or less")
# Ignoring specific cases
for num in range(1, 11):
if num == 5:
pass # Intentionally do nothing for 5
else:
print(num, end=" ") # 1 2 3 4 6 7 8 9 10
The else Clause with Loops
The else block after a loop runs only if the loop completes normally (without break).
# else with for loop
print("Searching for 6 in [1, 2, 3, 4, 5]:")
for num in [1, 2, 3, 4, 5]:
if num == 6:
print("Found 6!")
break
else:
print("6 not found in list")
# else with for loop (found case)
print("\nSearching for 3 in [1, 2, 3, 4, 5]:")
for num in [1, 2, 3, 4, 5]:
if num == 3:
print("Found 3!")
break
else:
print("3 not found in list")
# Prime number checker
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
else:
return True
# Test prime numbers
for num in [2, 17, 18, 23, 25]:
print(f"{num} is prime: {is_prime(num)}")
Comparison Table
| Statement | Purpose | Use Case |
|---|---|---|
break |
Exit loop immediately | Stop when target found |
continue |
Skip current iteration | Skip unwanted items |
pass |
Do nothing (placeholder) | Empty blocks |
else |
Run if no break occurred | Search completion check |
Practice Programming Examples
Example 1: Number Guessing Game
import random
# Number guessing game
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("š® Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print(f"You have {max_attempts} attempts.\n")
while attempts < max_attempts:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"š Congratulations! You got it in {attempts} attempts!")
break
remaining = max_attempts - attempts
if remaining > 0:
print(f"Attempts remaining: {remaining}\n")
else:
print(f"\nš¢ Game Over! The number was {secret}")
Example 2: FizzBuzz
# Classic FizzBuzz problem
# Print numbers 1-100, but:
# - Print "Fizz" for multiples of 3
# - Print "Buzz" for multiples of 5
# - Print "FizzBuzz" for multiples of both
for num in range(1, 101):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
Example 3: Pyramid Pattern
# Print pyramid pattern
rows = 5
print("Pyramid Pattern:")
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()
# Output:
# *
# ***
# *****
# *******
# *********
# Inverted pyramid
print("\nInverted Pyramid:")
for i in range(rows, 0, -1):
for j in range(rows - i):
print(" ", end="")
for k in range(2 * i - 1):
print("*", end="")
print()
Example 4: Prime Numbers
# Find all prime numbers up to n
n = 50
primes = []
for num in range(2, n + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
print(f"Prime numbers up to {n}:")
print(primes)
# Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Example 5: Simple Calculator
# Simple calculator with loop
print("š§® Simple Calculator")
print("Operations: +, -, *, /, ** (power)")
print("Type 'quit' to exit\n")
while True:
expression = input("Enter expression (e.g., 5 + 3): ")
if expression.lower() == 'quit':
print("Goodbye!")
break
try:
# Parse the expression
parts = expression.split()
num1 = float(parts[0])
operator = parts[1]
num2 = float(parts[2])
# Perform calculation
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("Error: Division by zero!")
continue
result = num1 / num2
elif operator == '**':
result = num1 ** num2
else:
print("Invalid operator!")
continue
print(f"Result: {result}\n")
except (ValueError, IndexError):
print("Invalid input! Use format: number operator number\n")
Practice Tip
Try modifying these examples! Add new features, handle edge cases, or combine multiple concepts to strengthen your understanding.