Week 5: Automating Repetitive Tasks with Loops

Learn how to use `for` and `while` loops in Python to execute code repeatedly.

Explore Chapter 5

Chapter 5: Repeating Actions with `for` and `while` Loops

`for` Loops: Iterating Over Sequences.

`for` loops in Python are designed to iterate over a sequence (like a list, tuple, string, or the result of the `range()` function) or other iterable objects. They execute a block of code for each item in the sequence.

Syntax

for item in sequence:
    # Code to be executed for each item
    print(item)
  • The `for` keyword is followed by a variable name (`item` in this case), which will take on the value of each element in the sequence during each iteration.
  • The `in` keyword is followed by the sequence you want to iterate over.
  • The colon `:` marks the beginning of the loop's code block.
  • The indented code block will be executed once for every item in the sequence.

Iterating Over Strings

text = "Python"
for char in text:
    print(char)

Output:

P
y
t
h
o
n

Iterating Over Lists

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

Output:

I like apple
I like banana
I like cherry

Using the `range()` Function

The `range()` function is often used with `for` loops to iterate a specific number of times. `range(stop)` generates a sequence of numbers from 0 up to (but not including) `stop`. `range(start, stop)` generates numbers from `start` up to `stop`. `range(start, stop, step)` generates numbers from `start` up to `stop` with a specified increment.

for i in range(5):  # Generates 0, 1, 2, 3, 4
    print(i)

for j in range(2, 7): # Generates 2, 3, 4, 5, 6
    print(j)

for k in range(0, 10, 2): # Generates 0, 2, 4, 6, 8
    print(k)

`while` Loops: Repeating Actions Based on a Condition.

A `while` loop repeatedly executes a block of code as long as a specified condition remains true.

Syntax

while condition:
    # Code to be executed as long as the condition is True
    statement1
    statement2
    # ...
    # Make sure the condition will eventually become False to avoid an infinite loop!
  • The `while` keyword is followed by a condition (a boolean expression).
  • The colon `:` marks the beginning of the loop's code block.
  • The indented code block will continue to execute as long as the `condition` evaluates to `True`.
  • It's crucial to ensure that something within the loop's body will eventually make the `condition` false, otherwise, you'll create an infinite loop that will run indefinitely.

Example

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

Output:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4

Another Example: Getting User Input Until a Condition is Met

password = ""
while password != "secret":
    password = input("Enter the password: ")
    if password != "secret":
        print("Incorrect password. Try again.")
print("Password accepted!")

`break` and `continue` Statements: Controlling Loop Execution.

The `break` and `continue` statements provide ways to alter the normal flow of `for` and `while` loops.

`break` Statement

The `break` statement immediately terminates the loop it is inside of. The program control then flows to the statement immediately following the loop.

numbers = [1, 2, 3, 4, 5, -1, 6, 7]
for num in numbers:
    if num < 0:
        print("Negative number found! Exiting loop.")
        break
    print("Number is:", num)

Output:

Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
Negative number found! Exiting loop.

`continue` Statement

The `continue` statement skips the rest of the code inside the current iteration of the loop and proceeds to the next iteration.

numbers = [1, 2, -3, 4, -5, 6]
for num in numbers:
    if num < 0:
        print("Negative number encountered. Skipping.")
        continue
    print("Positive number is:", num)

Output:

Positive number is: 1
Positive number is: 2
Negative number encountered. Skipping.
Positive number is: 4
Negative number encountered. Skipping.
Positive number is: 6

Nested Loops: Loops Inside Loops.

Just like conditional statements, you can also nest loops within other loops. This means you can have a `for` loop inside another `for` loop, a `while` loop inside a `for` loop, and so on.

Example: Nested `for` Loops

This example demonstrates how to iterate through rows and columns using nested `for` loops.

for i in range(3):      # Outer loop (for rows)
    for j in range(2):  # Inner loop (for columns)
        print(f"({i}, {j})")

Output:

(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)

Example: `while` loop inside a `for` loop

fruits = ["apple", "banana"]
i = 0
for fruit in fruits:
    count = 0
    print(f"Processing {fruit}:")
    while count < 2:
        print(f"- {fruit} - step {count}")
        count += 1

Output:

Processing apple:
- apple - step 0
- apple - step 1
Processing banana:
- banana - step 0
- banana - step 1

Nested loops are useful for tasks that involve iterating over multiple dimensions of data or performing repetitive actions within other repetitive actions.

Syllabus