Autocodewizard Logo Loops - For and While -Autocodewizard Ebooks - Python Programming Essentials: A Beginner�s Guide to Code and Data

Chapter 5: Loops � For and While

Understand loops in Python, including for and while loops, to repeat actions and iterate through data.

In this chapter, we�ll explore Python�s looping mechanisms, focusing on for and while loops. Loops are essential in programming, as they allow us to repeat tasks and process collections of data efficiently.

The for Loop

The for loop is commonly used to iterate over a sequence, such as a list or a range of numbers. Here�s an example:

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

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

Using the range() Function

The range() function is often used with for loops to iterate a specific number of times. By default, range() starts at 0 and increments by 1.

for i in range(5):
    print(i)

This loop prints numbers from 0 to 4. You can also specify a start and an end, such as range(2, 6) to print from 2 to 5.

The while Loop

The while loop continues executing as long as a given condition remains true. It�s ideal for scenarios where the number of iterations isn�t predetermined:

count = 0
while count < 5:
    print("Count is:", count)
    count += 1

In this example, the while loop continues to run until count is no longer less than 5.

Break and Continue Statements

The break and continue statements give you more control over loop execution:

for i in range(10):
    if i == 5:
        break
    print(i)

In this example, the loop stops when i equals 5 due to the break statement.

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

In this example, the continue statement skips even numbers, so only odd numbers are printed.

Nested Loops

You can place a loop inside another loop to handle more complex tasks. Here�s an example of a nested for loop:

for i in range(3):
    for j in range(2):
        print(f"i = {i}, j = {j}")

In this example, the inner loop runs fully for each iteration of the outer loop, producing a combination of i and j values.

Summary and Next Steps

In this chapter, we covered the for and while loops in Python, as well as techniques to control loops with break and continue. Loops allow you to handle repetitive tasks and iterate over data structures. In the next chapter, we�ll look into functions, which allow you to write modular, reusable code.