PythonProgramming Basics

Python Loops & Iterations: Master For, While and Else Clauses

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

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
    1for item in sequence: 2 # Code to execute for each item

    Example: Iterating over a List

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

    Example: Calculating a Sum

    python
    1numbers = [10, 20, 30, 40] 2total = 0 3for num in numbers: 4 total += num 5print(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
    1while condition: 2 # Code to repeat 3 # Modification to condition (to avoid infinite loops)

    Example: Finding a Key

    python
    1numbers = [2, 3, 4, 1, 5] 2target = 1 3i = 0 4 5while i < len(numbers): 6 if numbers[i] == target: 7 print(f"Found {target} at index {i}!") 8 break 9 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
    1matrix = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5] 6 7for row in matrix: 8 for item in row: 9 print(item, end=' ') 10 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
    1# Multiples of 3 under 10 2for i in range(3, 10, 3): 3 print(i) # Output: 3, 6, 9 4 5# Counting backwards 6for i in range(10, 0, -2): 7 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
      1for i in range(1, 10): 2 if i == 5: 3 break # Exit loop when i is 5 4 print(i)

      continue Example

      python
      1for i in range(1, 6): 2 if i == 3: 3 continue # Skip printing 3 4 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
      1for i in range(10): 2 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
      1# Searching for a number 2numbers = [1, 2, 3, 4, 5] 3target = 10 4 5for n in numbers: 6 if n == target: 7 print("Found it!") 8 break 9else: 10 print("Target was not in the list.")

      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.