Skip to Content
Course content

2.4.2 Loops: for, while

In Python, loops are used to repeat a block of code multiple times. There are two main types of loops: for loop and while loop.

1. for Loop

The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in that sequence.

Syntax:
for variable in sequence:
    # block of code
  • variable: A temporary variable that takes the value of each item in the sequence during each iteration.
  • sequence: A collection of items, such as a list, tuple, or range, that the loop will iterate over.
Example 1: Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
  • Explanation: This loop will iterate over each element in the fruits list and print each one:
    apple
    banana
    cherry
    
Example 2: Using range() for iteration

The range() function is commonly used with the for loop to specify a sequence of numbers.

for i in range(1, 6):  # Iterates over numbers from 1 to 5
    print(i)
  • Explanation: The range(1, 6) generates numbers from 1 to 5 (excluding 6), and the loop prints each number:
    1
    2
    3
    4
    5
    

2. while Loop

The while loop executes as long as a given condition is True. It will repeatedly execute the block of code inside it until the condition becomes False.

Syntax:
while condition:
    # block of code
  • condition: A boolean expression that is checked before each iteration. If it is True, the loop continues; if it is False, the loop stops.
Example 1: Basic while loop
counter = 1
while counter <= 5:
    print(counter)
    counter += 1  # Increment counter to avoid infinite loop
  • Explanation: This loop prints the numbers 1 to 5. The condition counter <= 5 is checked before each iteration, and after printing the counter, it is incremented by 1. The loop ends when the counter reaches 6.
    1
    2
    3
    4
    5
    
Example 2: Infinite loop (be careful!)
while True:
    print("This is an infinite loop")
    break  # Prevents it from running infinitely
  • Explanation: The condition True makes this an infinite loop, which will run indefinitely. However, we use break to exit the loop after one iteration.

3. Breaking and Continuing Loops

  • break: The break statement is used to exit the loop prematurely, regardless of the condition. It stops the loop completely and allows the program to continue with the next line of code after the loop.
    for i in range(1, 6):
        if i == 3:
            break  # Exit loop when i is 3
        print(i)
    
    • Explanation: This will print:
      1
      2
      
      When i becomes 3, the break statement is triggered, and the loop ends.
  • continue: The continue statement skips the current iteration and continues with the next iteration of the loop.
    for i in range(1, 6):
        if i == 3:
            continue  # Skip when i is 3
        print(i)
    
    • Explanation: This will print:
      1
      2
      4
      5
      
      When i equals 3, the continue statement skips the current iteration, so 3 is not printed.

4. Nested Loops

You can also nest loops inside each other. For example, you might use a for loop inside a while loop, or vice versa.

for i in range(1, 4):
    for j in range(1, 4):
        print(f"i = {i}, j = {j}")
  • Explanation: This will print a combination of all pairs of i and j:
    i = 1, j = 1
    i = 1, j = 2
    i = 1, j = 3
    i = 2, j = 1
    i = 2, j = 2
    i = 2, j = 3
    i = 3, j = 1
    i = 3, j = 2
    i = 3, j = 3
    

Summary of Key Points:

  • for loop: Used to iterate over a sequence (e.g., list, tuple, string, or range).
  • while loop: Used to repeat code as long as a condition is True.
  • break: Used to exit a loop prematurely.
  • continue: Skips the current iteration and moves to the next.
  • Nested loops: One loop inside another to handle complex iteration patterns.

Loops allow you to automate repetitive tasks and process large amounts of data efficiently. They are essential for most programming scenarios.

Commenting is not enabled on this course.