Loops are a tool that allows us to repeat a block of code multiple times. In Python, we have two main types of loops: for and while.
If you want to learn more, check out the Introduction to Programming Course
for Loop
The for loop is used to iterate over a sequence (like a list, tuple, dictionary, etc.) and execute a block of code for each element in that sequence.
The basic syntax of the for loop is as follows:
for element in sequence:
# block of code to execute for each element
for Loop Examples
Iterate over a collection
For example, we can use a for loop to print each element of a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this case, the for loop iterates over the fruits list and in each iteration, assigns the value of the current element to the variable fruit, which is then printed. The output will be:
apple
banana
cherry
Iterate a specific number of times
We can also use the for loop to perform a specific number of iterations, for example, a fixed number of times.
This is achieved using the range() function, which generates a sequence of numbers within a given range.
# Example of for loop with range(5)
for i in range(5):
print(i)
In this example, range(5) generates a sequence of numbers from 0 to 4 (excluding 5), and the for loop iterates over each of these numbers, assigning them to the variable i in each iteration. Then, the value of i is printed, resulting in the output:
0
1
2
3
4
By combining range() with a for loop, we can iterate over this sequence and execute a block of code a predetermined number of times.
Iterate over a text string
In addition to iterating over lists and other sequences, the for loop in Python can be used to iterate over other data types, such as text strings. This is because a text string is a collection of characters.
When we use a for loop with a text string, each iteration of the loop will go through the individual characters of the string, allowing us to process or manipulate each one as needed.
# Example of for loop with a string
for letter in "Python":
print(letter)
In this case, the for loop iterates over each character of the text string "Python". In each iteration, the value of the current character is assigned to the variable letter, which is then printed. The output will be:
P
y
t
h
o
n
while Loop
The while loop is used to repeat a block of code while a condition is true. The basic syntax of the while loop is as follows:
while condition:
# block of code to execute while the condition is true
while Loop Examples
For example, we can use a while loop to count from 1 to 5:
counter = 1
while counter <= 5:
print(counter)
counter += 1
In this case, the while loop will execute while the condition is true, that is, while counter is less than or equal to 5. In each iteration, the value of counter is printed and then incremented by 1. The output will be:
1
2
3
4
5
It’s important to be careful with conditions in while loops, because if the condition never becomes false, the loop will run indefinitely, which can cause an infinite loop.
break and continue Statements
Inside loops in Python, we can also use the break and continue statements to control the flow of execution.
Terminates the loop and executes the block of code that comes after the loop.
Let’s see an example using break to exit a for loop:
fruits = ["apple", "banana", "cherry", "watermelon", "grape"]
for fruit in fruits:
print(fruit)
if fruit == "watermelon":
break
In this case, the for loop will print each fruit in the list until it reaches “watermelon”, at which point break will be executed and the loop will be interrupted.
On the other hand, continue allows us to skip to the next iteration without executing the rest of the block of code for that iteration. Let’s see an example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
continue
print(number)
In this example, the for loop iterates over the numbers in the numbers list. When it finds an even number (divisible by 2), continue is executed, which means the print(number) is not executed for that number and it skips to the next iteration.
In certain situations, break and continue can help improve code readability. But, in general, it’s not advisable to overuse them because they make it harder to follow the code flow.
Loops with else
In Python, loops can also have an else clause, which is executed when the loop finishes without having been interrupted by a break. Let’s see an example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 0:
break
else:
print("The loop has finished without finding the number 0")
In this case, since there is no 0 in the numbers list, the loop will execute completely and at the end it will print “The loop finished without finding the number 0”.
