PythonProgramming Basics

Python Loops & Iterations: Master For, While and Else

TT
TopicTrick Team
Python Loops & Iterations: Master For, While and Else

Python Loops: Quick Answer

Python has two loop types: the for loop (iterates over a sequence — list, string, range) and the while loop (repeats while a condition is True). Both support break to exit early, continue to skip an iteration, and a unique else clause that runs only when the loop completes without a break.

Introduction to Python Loops

In programming, we follow the DRY (Don't Repeat Yourself) principle. Instead of writing the same code multiple times, we use Loops to automate repetitive tasks.

A loop allows you to execute a block of code multiple times by iterating over a sequence (like a list, dictionary, or string) or until a specific condition is met.

The Golden Rule of Loops

Every loop must have a terminating condition. Without one, you create an 'infinite loop' that can crash your program!


    1. The Python for Loop

    The for loop is used when you want to iterate over a sequence. It is the most common way to access every element in a collection.

    Syntax

    python
    for item in sequence:
        # Code to execute for each item

    Example: Iterating over a List

    python
    fruits = ['Apple', 'Banana', 'Cherry']
    for fruit in fruits:
        print(f"I love {fruit}")

    Example: Calculating a Sum

    python
    numbers = [10, 20, 30, 40]
    total = 0
    for num in numbers:
        total += num
    print(f"The total sum is: {total}")

    2. The Python while Loop

    The while loop repeats a section of code as long as a condition is True. It is an "entry-controlled" loop, meaning the condition is checked before the code runs.

    Syntax

    python
    while condition:
        # Code to repeat
        # Modification to condition (to avoid infinite loops)

    Example: Finding a Key

    python
    numbers = [2, 3, 4, 1, 5]
    target = 1
    i = 0
    
    while i < len(numbers):
        if numbers[i] == target:
            print(f"Found {target} at index {i}!")
            break
        i += 1

    3. Nested Loops

    Python allows you to put one loop inside another. This is particularly useful for working with 2D data like matrices or grids.

    Example: Traversing a 2D Matrix

    python
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    
    for row in matrix:
        for item in row:
            print(item, end=' ')
        print() # New line after each row

    4. The range() Function

    The range() function is a lifesaver when you need to run a loop a specific number of times. It generates an arithmetic progression lazily (saving memory).

    ParameterDescription
    StartBeginning of the range (default is 0)
    StopThe end point (exclusive)
    StepThe increment between numbers (default is 1)

    Examples

    python
    # Multiples of 3 under 10
    for i in range(3, 10, 3):
        print(i) # Output: 3, 6, 9
    
    # Counting backwards
    for i in range(10, 0, -2):
        print(i) # Output: 10, 8, 6, 4, 2

    5. Loop Control: break, continue, and pass

    Sometimes you need to change how a loop behaves on the fly.

    Break vs Continue

    Break exits the loop entirely. Continue skips the rest of the current iteration and jumps to the next one.

      break Example

      python
      for i in range(1, 10):
          if i == 5:
              break # Exit loop when i is 5
          print(i)

      continue Example

      python
      for i in range(1, 6):
          if i == 3:
              continue # Skip printing 3
          print(i)

      pass Example

      The pass statement is a null operation. It's used as a placeholder for code you haven't written yet.

      python
      for i in range(10):
          pass # I'll add logic here later!

      6. The Unique else Clause in Loops

      One of Python's most unique features is the else clause for loops. The else block executes only if the loop finishes naturally (i.e., it wasn't stopped by a break).

      Logic:

      • Loop finished? → else runs.
      • Loop broken? → else is skipped.
      python
      # Searching for a number
      numbers = [1, 2, 3, 4, 5]
      target = 10
      
      for n in numbers:
          if n == target:
              print("Found it!")
              break
      else:
          print("Target was not in the list.")

      7. Looping with enumerate() and zip()

      Two extremely useful built-in functions for cleaner loop patterns:

      python
      # enumerate() — get both index and value
      fruits = ["apple", "banana", "cherry"]
      for i, fruit in enumerate(fruits, start=1):
          print(f"{i}. {fruit}")
      # 1. apple
      # 2. banana
      # 3. cherry
      
      # zip() — iterate over two lists in parallel
      names = ["Alice", "Bob", "Carol"]
      scores = [95, 82, 78]
      
      for name, score in zip(names, scores):
          print(f"{name}: {score}")
      # Alice: 95
      # Bob: 82
      # Carol: 78

      Both are far more Pythonic than using a manual counter variable.

      8. List Comprehensions: Loops in One Line

      A list comprehension is a concise loop that builds a list in a single expression:

      python
      # Standard loop
      squares = []
      for x in range(1, 6):
          squares.append(x ** 2)
      
      # Equivalent comprehension
      squares = [x ** 2 for x in range(1, 6)]
      print(squares)  # [1, 4, 9, 16, 25]
      
      # With a filter condition
      even = [x for x in range(20) if x % 2 == 0]
      print(even)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

      For more on comprehensions, see Python Lists: Complete Guide.

      Real-World Example: Processing a Dictionary

      Combining loops with dictionaries is one of the most common Python patterns:

      python
      stock = {"apples": 5, "bananas": 0, "oranges": 3, "grapes": 0}
      
      # Find all out-of-stock items
      out_of_stock = [item for item, qty in stock.items() if qty == 0]
      print(f"Out of stock: {out_of_stock}")  # ['bananas', 'grapes']
      
      # Restock all items to a minimum of 10
      restocked = {item: max(qty, 10) for item, qty in stock.items()}
      print(restocked)

      Related Python Topics

      For the official reference, see Python for statements and enumerate() in the Python documentation.

      Conclusion

      Mastering loops is a fundamental step in becoming a Python pro. Whether you are using for for collections or while for conditions, always remember to keep your logic clean and your terminating conditions sharp.

      Happy coding!

      Next Step

      Combine your knowledge of loops with Conditionals to build powerful, decision-making algorithms.

        Common Loop Mistakes in Python

        1. Using range(len(lst)) instead of enumerate for i in range(len(lst)): print(lst[i]) works but is un-Pythonic. Use for i, val in enumerate(lst): to get both the index and value cleanly. See the Python built-in functions documentation.

        2. Modifying a list while iterating Removing elements from a list inside a for loop causes skipped elements. Iterate over a copy (for item in lst[:]) or filter with a list comprehension: lst = [x for x in lst if condition(x)].

        3. Forgetting that while True needs an explicit break An infinite while True: loop without a guaranteed break hangs the program. Always ensure at least one code path reaches break or return.

        4. Using for where any() or all() is cleaner

        python
        # verbose
        found = False
        for x in lst:
            if x > 0:
                found = True
                break
        # idiomatic
        found = any(x > 0 for x in lst)

        Generator expressions with any() and all() short-circuit and are more readable.

        5. Ignoring itertools for complex iteration patterns itertools.chain, itertools.product, itertools.groupby, and itertools.islice cover most advanced iteration needs without manual loops. The itertools documentation is worth bookmarking.

        Frequently Asked Questions

        What is the difference between break, continue, and pass? break exits the loop immediately. continue skips the rest of the current iteration and moves to the next. pass is a no-op placeholder that does nothing — useful in empty except blocks or stub functions.

        Does Python's for loop have an else clause? Yes — for ... else: runs the else block if the loop completed without hitting a break. It is useful for "search and not found" patterns: iterate searching for an item, break if found, and the else block handles the "not found" case.

        What is the fastest way to iterate over a large dataset in Python? For very large datasets, use generators (yield) to process items one at a time without loading everything into memory. For numerical data, NumPy vectorised operations are orders of magnitude faster than Python loops. The Python generator documentation covers lazy iteration patterns.