Topic 9 - Loops
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks
without making errors is something that computers do well and people do poorly. Because
iteration is so common, Python provides several language features to make it easier.
For loops
The for loop in Python is used to execute a block of code repeatedly for each item in a
sequence or collection, such as a list, string, or tuple. The loop continues running until there
are no more items left to process.
Looping through an iterable
In Python, an iterable refers to any object that can be looped over, such as a string, list, or
tuple. The syntax for looping through an iterable is as follows:
for a in iterable:
print(a)
Example:
pets = ['cats', 'dogs', 'rabbits', 'hamsters']
for myPets in pets:
print(myPets)
Output:
cats
dogs
rabbits
hamsters
In the program above:
1. The list pets contains four elements: 'cats', 'dogs', 'rabbits', and 'hamsters'.
2. The statement for myPets in pets: means:
○ On the first loop, myPets is 'cats'.
○ On the second loop, myPets is 'dogs'.
○ On the third and fourth loops, myPets becomes 'rabbits' and 'hamsters',
respectively.
3. The print(myPets) statement prints the value of myPets each time the loop runs.
Looping Through a String
A string is also an iterable in Python. You can loop through each character in a string one by
one.
Example:
message = 'Hello'
for i in message:
print(i)
Output:
H
e
l
l
o
By default, the print() function adds a new line after each output. You can change this behavior
using the end argument to control what is printed at the end of each iteration.
Example: With Space
message = 'Hello'
for i in message:
print(i, end=' ')
Output:
H e l l o
Example: No Character
message = 'Hello'
for i in message:
print(i, end='')
Output:
Hello
Example: With Character
message = 'Hello'
for i in message:
print(i, end='|')
Output:
H|e|l|l|o|
Looping Through a Sequence of Numbers
To loop through a sequence of numbers, Python provides the built-in range() function. This
function generates a sequence of numbers that can be used in a for loop and has the syntax:
range(start, end, step)
● start – the starting number (default is 0 if not specified)
● end – the number at which the sequence stops (not included)
● step – the increment between numbers (default is 1)
Example: Using range() with One Argument
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example: Using range() with Start and End
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Example: Using range() with Start, End, and Step
for i in range(1, 6, 2):
print(i)
Output:
1
3
5
Using a for Loop to Perform Calculations
A for loop can also be used to process data or perform arithmetic operations, such as
calculating the sum of numbers in a list.
Example: Adding Numbers in a List
num_list = [1, 2, 3, 4, 5]
total = 0
for num in num_list:
total = total + num
print("The total is:", total)
Output:
The total is: 15
The while loop
The next control flow statement we will look at is the while loop. As its name suggests, a while
loop repeatedly executes a block of code as long as a certain condition remains true. The
structure of a while statement is as follows:
while condition is true:
do A
Most of the time when using a while loop, we need to first declare a variable to function as a
loop counter. Let’s just call this variable counter. The condition in the while statement will
evaluate the value of the counter to determine if it is smaller (or greater) than a certain value. If
it is, the loop will be executed. Refer to the sample program below.
Example:
counter = 5
while counter > 0:
print("Counter =", counter)
counter = counter - 1
Output:
Counter = 5
Counter = 4
Counter = 3
Counter = 2
Counter = 1
In the code:
1. The variable counter is initialized with the value 5.
2. The condition counter > 0 is checked before every iteration.
3. Inside the loop:
○ The current value of counter is printed.
○ The statement counter = counter - 1 decreases the counter by one each time.
4. When counter reaches 0, the condition becomes false, and the loop stops.
Important Note: Avoiding Infinite Loops
Be careful when using while loops. Forgetting to update your loop variable can cause an
infinite loop. If you remove the line counter = counter - 1 in the program above, the loop will
never end because the counter will always remain 5.
This results in the program printing Counter = 5 endlessly until it is manually stopped.
Infinite loops can freeze your program or system, especially in large programs where it’s hard
to find the source of the problem.
The break Statement
When working with loops, you might want to exit the loop early when a certain condition is met.
The break keyword allows you to immediately stop the entire loop, even if its condition is still
true.
Example:
counter = 1
while counter <= 10:
print("Counter =", counter)
if counter == 5:
print("Loop stopped because counter reached 5.")
break
counter = counter + 1
Output:
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
Loop stopped because counter reached 5.
In the code above:
1. The loop starts with counter = 1 and continues as long as counter <= 10.
2. Each time the loop runs, it prints the value of counter.
3. When counter becomes 5, the condition if counter == 5: becomes true.
4. The break statement executes, ending the loop immediately, even though the condition
counter <= 10 is still true.
The continue Statement
The continue keyword is used to skip the rest of the code inside the loop for the current
iteration and move to the next one. This is useful when you want to ignore specific cases
during looping.
Example:
counter = 0
while counter < 5:
counter = counter + 1
if counter == 3:
print("Skipping number 3.")
continue
print("Current number:", counter)
Output:
Current number: 1
Current number: 2
Skipping number 3.
Current number: 4
Current number: 5
In the code above:
1. The loop runs as long as counter is less than 5.
2. Each iteration increases counter by 1.
3. When counter becomes 3:
○ The message "Skipping number 3." is printed.
○ The continue statement executes, skipping the rest of the code inside the loop
(so print("Current number:", counter) is not executed for 3).
4. The loop then continues to the next iteration.