Language: EN

python-bucles

Loops in Python

Loops are a tool that allows us to repeat a block of code several times. In Python, we have two main types of loops: for and while.

Loop for

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

Examples for loop

Iterate over a collection For example, we can use a for 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 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
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 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 traverse 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
n

Loop while

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

Examples while loop

For example, we can use a while to count from 1 to 5:

counter = 1

while counter <= 5:
    print(counter)
    counter += 1

In this case, the while loop will run as long as the condition is true, that is, as long as 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 is important to be careful with the 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

Within loops in Python, we can also use the break and continue statements to control the flow of execution.

  • break: It terminates the loop and executes the block of code that comes after the loop.
  • continue: It jumps to the next iteration of the loop, ignoring the rest of the block of code for that iteration.

In certain situations break and continue improve code readability. But it is not advisable to get used to or abuse them because, in general, they make it difficult to follow the flow of code.

Break

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 from the list until it reaches “watermelon”, at which point break will be executed and the loop will be interrupted.

Continue

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, meaning that print(number) is not executed for that number and it jumps to the next iteration.

Loops with else

In Python, loops can also have an else clause, which is executed when the loop finishes 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 be executed completely and at the end “The loop has finished without finding the number 0” will be printed.