Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 3 - Control Flow

3.2 Loops

Loops in Python allow you to execute a block of code repeatedly, making it efficient for tasks that require repetitive operations.

for Loop:

The for loop is used to iterate over a sequence such as a list, tuple, or string. Here’s how you create a for loop:

fruits = ["orange", "banana", "apple"]
for fruit in fruits:
    print(fruit)

In this example, the for loop iterates through each item in the fruits list and prints it.

while Loop:

The while loop executes a block of code as long as a specified condition is True. For example:

count = 0
while count < 5:
    print(count)
    count += 1

This while loop runs until the count variable is less than 5. The count += 1 statement increments count by one with each iteration.

Interrupting Loops:

break Statement:

The break keyword interrupts the loop execution immediately when a certain condition is met. For instance:

count = 0
while count < 5:
    if count == 3:
        break
    print(count)
    count += 1

In this example, the loop stops as soon as count equals 3, due to the break statement.

continue Statement:

The continue keyword skips the current iteration of the loop when a specified condition is True. For example:

count = 0
while count < 5:
    if count == 3:
        count += 1
        continue
    print(count)
    count += 1

Here, the loop skips printing when count equals 3, but continues with the next iteration.

These control flow statements (break and continue) are powerful tools for managing loop execution based on specific conditions in Python.