Python For & While Loops: Enumerate, Break, Continue Statement

Created with Sketch.

In Python, you can use for and while loops to iterate over sequences or execute a block of code repeatedly. Here are examples of using for and while loops, along with the enumerate, break, and continue statements:

for Loop with enumerate:

The enumerate function is used to iterate over both the elements and their indices in a sequence.

fruits = ["apple", "banana", "cherry"]

# Using for loop with enumerate
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

for Loop with break:

The break statement is used to exit a loop prematurely.

numbers = [1, 2, 3, 4, 5]

# Using for loop with break
for number in numbers:
    if number == 3:
        print("Found 3. Exiting loop.")
        break
    print(f"Processing {number}")

for Loop with continue:

The continue statement is used to skip the rest of the code inside the loop for the current iteration.

numbers = [1, 2, 3, 4, 5]

# Using for loop with continue
for number in numbers:
    if number == 3:
        print("Skipping 3.")
        continue
    print(f"Processing {number}")

while Loop with break:

The break statement is also used in while loops to exit the loop prematurely.

count = 0

# Using while loop with break
while count < 5:
    print(f"Count: {count}")
    count += 1
    if count == 3:
        print("Breaking the loop.")
        break

while Loop with continue:

The continue statement is used in while loops to skip the rest of the code inside the loop for the current iteration.

count = 0

# Using while loop with continue
while count < 5:
    count += 1
    if count == 3:
        print("Skipping count 3.")
        continue
    print(f"Count: {count}")

These examples illustrate the use of for and while loops along with enumerate, break, and continue statements in Python. You can adapt these concepts based on the specific requirements of your code.

Leave a Reply

Your email address will not be published. Required fields are marked *