Topic 2: Loops (while, for)

1. Introduction

Loops are a fundamental programming concept that allow for a set of instructions to be executed repeatedly based on a condition or a sequence. Python supports two primary types of loops: while and for.

2. The while Loop

The while loop repeatedly executes its block of code as long as its condition remains True.

Syntax:

python
while condition: # code to execute while condition is True

Example:

python
count = 0 while count < 5: print(count) count += 1

3. The for Loop

The for loop is used to iterate over sequences (like lists, tuples, strings) or other iterable objects.

Syntax:

python
for variable in sequence: # code to execute for each item in sequence

Example with a List:

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

4. The range() Function

The range() function generates a sequence of numbers and is often used with the for loop to iterate a certain number of times.

Syntax and Variations:

python
range(stop) # from 0 to stop-1 range(start, stop) # from start to stop-1 range(start, stop, step) # from start to stop-1 with step increments

Example:

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

5. Nested Loops

Loops can be nested within each other to handle more complex scenarios.

Example:

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

6. break and continue Statements

  • break: Exits the current loop entirely.
  • continue: Skips the remaining code in the current iteration and moves to the next iteration.

Example:

python
for i in range(5): if i == 3: break print(i) # Outputs: 0, 1, 2 for i in range(5): if i == 3: continue print(i) # Outputs: 0, 1, 2, 4

7. else Clause in Loops

An often-overlooked feature is the else clause in loops. It executes after the loop completes normally (i.e., without encountering a break).

Example:

python
for i in range(5): print(i) else: print("Loop completed!")

8. List Comprehensions

List comprehensions provide a concise way to create lists using a loop.

Syntax:

python
[expression for item in iterable if condition]

Example:

python
squared_numbers = [x**2 for x in range(5) if x % 2 == 0] print(squared_numbers) # Outputs: [0, 4, 16]

9. Conclusion

Loops empower developers to perform repetitive tasks efficiently and are foundational in algorithm development. Grasping the intricacies of while and for loops, coupled with mastery over associated control statements like break and continue, ensures that a programmer can craft solutions for a wide array of challenges. As always, the key lies in practice and application, ensuring that these concepts are internalized and readily recalled when needed.