Introduction to Computing –
Python (IS086IU)
Chapter 4: Looping
Overview
Introduction to Loop Structures
The for Loop
The while Loop
Loop Control Statements
2
Loop Structures
• Allows us to repeat a block of
code multiple times
• Without writing code over
and over
• Makes code shorter, clearer,
and more efficient
Without using a loop Using a for-loop
print(1**2)
print(2**2)
print(3**2) for i in range(1, 7):
print(4**2) print(i**2)
print(5**2)
print(6**2)
3
Loop Structures - Categories
• for-loop: iterates over a sequence
• Like a list, string, range, set, dict etc
• Use of range(start, stop, step)
• while-loop: repeats as long as a condition is True
• break and continue: controls flow in loops
• break: exits the loop entirely
• continue: skips to the next iteration
4
For-Loop Start
• Goes through each item in a sequence, For item in a
like a list or string sequence
• The number of elements is known in
advance Last
item Yes
• Syntax: Stop
reached
Next
for x in iterable: ?
No
# do something with x
# Do something
5
For-Loop – Example
The range() function
for char in “hello”: “h” defaults to 0 as a starting
print(char) “e” value, however it is
“l” possible to specify the
starting value by adding a
“l” parameter: range(1, 6),
“o” which means values from 1
to 6 (but not including 6):
total = 0
for num in range(1, 6, 1):
total = total + num
print(total) 15
6
For-Loop – Example
Code Output Comment
fruits = ["apple", "cherry", "grape"] apple The loop assigns each element from the fruits
for f in fruits: cherry list, in order, to a loop variable named f
print(f) grape
x = 1 The character _ in a Python for is a dummy
for _ in range(3): variable.
x += 1 Inside the loop, the variable _ is not used
print(x) 4
for i in range(1, 3): (1,5) Nested for loop
for j in range(5, 7): (1,6)
print(i, j) (2,5)
(2,6)
7
Enumerate & Zip
Code Output Comment
0: apple # enumerate: returns both
1: cherry index and the value during
2: grape iteration
Alice scored 85 # Use zip() to iterate over both lists
Bob scored 90 simultaneously
Charlie scored 78 # Use an f-string to print the
formatted result
8
Nested Loops
• A loop inside another loop • Syntax:
• Example:
for i in range(1, 4): for x in outer_range:
for j in range(1, 4): for y in inner_range:
print(i*j, end = ' ') # do something with x & y
print() # Do something with x
• Output:
1 2 3
• Use with caution when:
2 4 6
• The dataset is large
3 6 9 • Running time is critical
• More than 2-3 levels of nested loops
9
Example: nested Loops
Code Output Comment
1 2 3 # Outer Loop for i in range(1, 4):
2 4 6 # Inner Loop for j in range(1, 4):
3 6 9 # end = ‘ ’ is a keyword tells
the print() function not to
start a new line after printing;
instead, it puts a single space
(' ') after the output. This
keeps the results for a single
row on the same line
# print()
This is inside the outer loop but outside
the inner loop.
After the inner loop finishes, it simply
prints a newline character
10
Example: nested Loops
Code Output Comment
1 2 3
2 4 6
3 6 9
11
While-Loop
• Keeps running a block of code as long
as a condition remains true Start
Next
• The number of loops is unknown in
advance No
Condition
• Syntax: Stop
is True?
while condition:
# do something Yes
• If the condition is always True, the
loop will run forever # Do something
12
While-Loop – Example
Code Output Comment
3
2
1
2 # n is decremented first, then
1 print n
0
Running forever
Running forever
Running forever
Running forever
Running forever
13
Flow Controls – break, continue, & else
Use break to escape the loop immediately
Code Result
0 Running no break
1 Running no break
2 Running no break
3 Break
14
Flow Controls – break, continue, & else
Use continue to skip one loop and move to the next loop
Code Result
1 The this line is executed
2 The this line is executed
4 The this line is executed
5 The this line is executed
Loop finished.
15
Flow Controls – break, continue, & else
• else block runs only if the for or while loop finishes without a
break or an (error) exception
Code Result
count = 0
while count < 3: 0 ‘Running forever’
print(count, "Running forever") 1 ‘Running forever’
count += 1 2 ‘Running forever’
else: "Finish without any
print("Finish without any break") break"
16
Flow Controls – break, continue, & else
• else block runs only if the for or while loop finishes without a
break or an (error) exception
Code Result
count = 0
while True:
if count == 3:
break
print(count, ‘Running forever’)
count += 1 0 ‘Running forever’
else: 1 ‘Running forever’
print(“This will not be shown”) 2 ‘Running forever’
17
Key Takeaways
• Use for when knowing how many times to loop
• Use while when the number of iterations is unknown in advance, but
depends on a condition
• Use break to stop the loop immediately under a specific condition
• Use continue to skip the rest of the loop body and move to the next
iteration
• Use else to detect whether the loop finished normally – without a
break
18
Self-study Questions
• What is an F-String in Python. Give some examples to demonstrate its
usefulness.
• What is the purpose of try … except block in Python? What is
ValueError? Give one example to demonstrate the try … except
19
Algorithmic Thinking
• Algorithm: The ability to solve problems using a clear sequence of
steps
• Key ideas:
• Decomposition: Breaking it down into smaller steps
• Pattern recognition: Identifying similarities or repeated logic
• Abstraction: Focusing on main details to simplify the problem
• Algorithm design: Creating a step-by-step solution using if, for, and while
• Make a pseudocode first
• Pseudocode: A way to describe an algorithm using logical steps and plain
language
• No need to follow Python, C++, Java, or any language rules
20
Algorithmic Thinking – Example 1
• Find the largest number from the list of [5, 3, 9, 1, 7]
• Pseudocode (to-do list style):
1. Assume the first number is the largest.
2. Go through each number in the list:
If a number is bigger than the current largest:
Update the largest number
Otherwise, move on to the next number
3. After the loop, the largest number is the answer
21
Algorithmic Thinking – Example 1
• Find the largest number from the list of [5, 3, 9, 1, 7]
• Pseudocode: • Python code:
1. Initialize the list 1. L = [5, 3, 9, 1, 7]
2. Set M = the first number in the list 2. M = L[0]
3. For each number in the given list: 3. for i in L:
1. If M < number: if M < L[i]:
2. Set M = number M = L[i]
4. Output M 4. Print(M)
22
Algorithmic Thinking – Example 2
• Calculate the sum of numbers in the list of [5, 3, 9, 1, 7]
• Pseudocode (to-do list style):
1. Start with a total of 0
2. Go through each number in the list:
Add the number to the total
3. After the loop, output the total
23
Algorithmic Thinking – Example 2
• Calculate the sum of numbers in the list of [5, 3, 9, 1, 7]
• Pseudocode: • Python code:
1. Set S = 0 1. L = [5, 3, 9, 1, 7]
2. For each number in the given 2. S = 0
list: 3. for i in L:
S = S + number: S = S + L[i]
3. Output M 4. Print(S)
24
Problem 1 – Feed me integers
Write a program which repeatedly reads integers until the user enters “done”.
-Once “done” is entered, print out the total, count, and average of the integers.
-If the user enters anything other than a integers, detect their mistake.
-Using try and except and print an error message and skip to the next integers.
Hint:
try:
#Convert the input string to an integer
….
Except ValueError
#Detect mistake if the input string is not an integer
25
Problem 2 – Min/Max detector
Exercise 2: Write another program that prompts for a list of numbers as above and at
the end prints out both the maximum and minimum of the numbers instead of the
average
26
Problem 3 – Password Validation
• Given a list of passwords, check if each password meets basic rules:
• At least 8 characters long (length >= 8)
• Having uppercase, lowercase, and numbers
passwords = [“hello”, “12345678”, “GoodPass1”,
“myPassword”, “HelloWorld007”]
27
Problem 4 – Customer Feedback Scanner
• Given a list of customer feedback strings
• Check if any contains the word “refund”
• If found, print “Refund request found: “Feedback” ” and stop checking immediately (Hint: You
might use for-else)
• If not found, print (“No refund request found”)
feedbacks = [“Great service!”,
“Where is my order?”,
“I want a refund now!”,
“Wonderful!”,
“I have no idea”]
28
Problem 5 – Find Overdue Bills
• Given a list of bills, each bill is a dictionary with a due_date and paid
status
• Write a loop to print all bills that are overdue and unpaid
from datetime import date
bills = [{“id”: 1, “due_date”: date(2025, 7, 1), “paid”: False},
{“id”: 2, “due_date”: date(2025, 8, 1), “paid”: True},
{“id”: 3, “due_date”: date(2025, 9, 1), “paid”: False},
{“id”: 4, “due_date”: date(2025, 6, 25), “paid”: False}]
today = date(2025, 8, 10)
29
Problem 6 – Recipe Ingredient Matcher
• Check if a user has all required ingredients to cook a recipe
• Hint: You might use for-else
required = [“eggs”, “milk”, “flour”, “butter”]
available = [“milk”, “flour”, “eggs”, “sugar”, “butter”,
“red peppers”, “salt”, “pork”, “beef”, “basil”]
30
Problem 7 – Salary Adjustment Tool
• Given a list of employees, apply a 5% raise only to those with ratings
>= 4.0
employees = [{“name”: “Alice”, “salary”: 50_000, “rating”: 4.2},
{“name”: “Bob”, “salary”: 48_000, “rating”: 3.8},
{“name”: “Emma”, “salary”: 51_000, “rating”: 4.5},
{“name”: “David”, “salary”: 32_000, “rating”: 4.0}]
31
Problem 8 – Invalid Email Check
• Given a list of emails, skip invalid ones and only print valid ones
• Hint: You might use continue
emails = [“john@[Link]”, “no_at_symbol”, “jane@[Link]”,
“invalid@”, “@missingname”, “hello@[Link]”]
32
Thanks for listening!
37