2. Topic 2(COLON) Programming Fundamentals in Python

Lesson 2.4: Iteration: Loops

#### Lesson focus #### Learning outcomes Students should be able to:.

Lesson 2.4: Iteration: Loops

In this lesson, we will dive into the concept of iteration and how to use loops in Python. By the end of this lesson, you will be able to understand and implement loops to repeat actions in your programs.

Learning Objectives

By the end of this lesson, students should be able to:

  • Understand and apply definite iteration using for loops and the range function.
  • Utilize indefinite iteration with while loops and set appropriate loop conditions.
  • Control loops effectively using accumulators, counters, early exit, and by avoiding infinite loops.
  • Implement nested loops and determine which type of loop is most suitable for a specific task.
  • Write both for and while loops to repeat actions a defined number of times or an unknown number of times.

Introduction to Iteration

Iteration is a fundamental concept in programming. Simply put, it allows us to repeat a block of code multiple times without rewriting it. Imagine you need to get 10 students' names and print them out. Instead of writing a print statement for each student, you can use a loop to handle this efficiently.

Definite Iteration with For Loops

For loops are used when you know in advance how many times you want to execute a block of code. A common use of for loops in Python is with the range function.

Example: Using a For Loop with Range

Here’s how you might use a for loop to print numbers from 0 to 4:

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

In this code, range(5) generates a sequence of numbers from 0 to 4. The print(i) statement will execute 5 times, printing each number in the sequence.

Indefinite Iteration with While Loops

In contrast, while loops allow for indefinite iteration. You use a while loop when you’re not sure how many times you want to repeat a certain block of code—this depends on a condition.

Example: Using a While Loop

Here’s a simple while loop that continues to print a message until a certain condition is met:

count = 0
while count < 5:
    print('Count is:', count)
    count += 1  # This increases count by 1 each time the loop runs

In this example, the loop will keep running as long as count is less than 5. Each time the loop runs, the count is incremented by 1 (thanks to count += 1), and once count reaches 5, the loop stops.

Loop Control: Accumulators and Counters

When working with loops, you may need to track specific values, which is where accumulators and counters come into play.

Example: Using an Accumulator

An accumulator keeps a running total. Let’s say you want to sum the numbers from 1 to 5:

sum = 0  # Initialize an accumulator
for number in range(1, 6):
    sum += number  # Add each number to the sum
print('Total sum:', sum)

This will output Total sum: 15 because $1 + 2 + 3 + 4 + 5 = 15$.

Loop Control: Early Exit and Avoiding Infinite Loops

Sometimes you might want to exit a loop early, especially if a certain condition is met. The break statement is essential in such cases. Conversely, you should be aware of how to avoid infinite loops, where a loop never ends.

Example: Early Exit with Break

for i in range(10):
    if i == 5:
        break  # Exit the loop when i equals 5
    print(i)

This will print numbers 0 through 4 and exit the loop when i is 5.

Nested Loops

A nested loop is a loop within another loop. This is useful when dealing with multi-dimensional data structures, such as lists of lists.

Example: Nested Loop

In the following example, we print a grid of stars:

for i in range(5):
    for j in range(5):
        print('*', end=' ')
    print()  # Move to the next line after finishing one row

This results in:

* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * * 

Choosing the Right Loop for a Task

When deciding whether to use a for or while loop, ask yourself:

  • Do I know how many times I need to repeat the action? If yes, use a for loop.
  • Is the number of repetitions uncertain? If so, go for a while loop.

Conclusion

In this lesson, we explored loops, an essential concept in programming. We covered different types of loops—for loops for definite iteration and while loops for indefinite iteration. We also discussed loop control techniques, including accumulators, early exits using break, and how to avoid infinite loops. Now that you know how to use loops effectively, you can avoid repetitive code and make your programs more efficient!

Study Notes

  • For Loops: Used for definite iteration; syntax is for variable in range(number):.
  • While Loops: Used for indefinite iteration; continues as long as a condition is true.
  • Accumulators: Variables that track totals or sums across iterations.
  • Counters: Variables that track the number of iterations.
  • Break Statement: Exits a loop prematurely.
  • Nested Loops: A loop within another loop, useful for multi-dimensional data.
  • Choosing Loops: Use for loops for known counts, while loops for unknown repetitions.

Practice Quiz

5 questions to test your understanding

Lesson 2.4: Iteration: Loops — Computing | A-Warded