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 about Loops
check the Introduction to Programming Course read more
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 elementExamples of for loop
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 goes through the list fruits 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
cherryIterate a 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 in 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
4By 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 string
In addition to iterating over lists and other sequences, the for loop in Python can be used to iterate over other types of data, such as strings. This is because a string is a collection of characters.
When we use a for loop with a string, each iteration of the loop will go through the individual characters of the string, allowing us to process or manipulate each of them 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 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
nwhile 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 trueExamples of while loop
For example, we can use a while loop to count from 1 to 5:
counter = 1
while counter <= 5:
print(counter)
counter += 1In this case, the while loop will execute as long as 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
5It is important to be careful with conditions in while loops, as if the condition never becomes false, the loop will run indefinitely, which can cause an infinite loop
break and continue Statements
Within loops in Python, we can also use the break and continue statements to control the flow of execution.
Ends the loop and executes the block of code that is 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":
breakIn this case, the for loop will print each fruit from the list until it reaches “watermelon”, at which point break will be executed and the loop will stop.
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 encounters an even number (divisible by 2), continue is executed, meaning that print(number) is not executed for that number, and it skips to the next iteration.
In certain situations, break and continue can help improve the readability of the code. However, in general, it’s best not to overuse them as they can make it difficult to follow the flow of the code.
Loops with else
In Python, loops can also have an else clause, which is executed when the loop ends without being 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 has finished without finding the number 0”.