python-bucles

Loops in Python

  • 5 min

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
Copied!

for Loop Examples

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
Copied!

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
Copied!

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)
Copied!

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")
Copied!

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”.