Understand Loops in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will gain a fundamental understanding of loops in Python, which are essential tools for automating repetitive tasks. We will begin by exploring for loops and the concept of iteration, learning how to process sequences like lists and strings.

Following this, you will discover how to use the range() function with for loops to generate sequences of numbers. We will then introduce while loops for condition-based repetition. Finally, you will learn how to control the flow of both for and while loops using the break and continue statements.

Introduce For Loops and Iteration

In this step, you will learn about the for loop in Python. A for loop is used to iterate over a sequence, such as a list, tuple, or string. Iterating means performing an action for each item in the sequence, one by one.

First, let's use a for loop to print each element of a list.

In the WebIDE file explorer on the left, you will see a list of files. Find and open the file named for_loop_example.py. Add the following Python code to it:

## Define a list of numbers
numbers = [1, 2, 3, 4, 5]

## The for loop iterates over each item in the 'numbers' list.
## In each iteration, the current item is assigned to the 'number' variable.
for number in numbers:
  ## This code block is executed for each item.
  print(number)

Save the file by pressing Ctrl + S.

To run the script, open the integrated terminal by clicking Terminal -> New Terminal at the top of the WebIDE. Then, execute the following command:

python for_loop_example.py

You should see the following output, with each number printed on a new line:

1
2
3
4
5

for loops can also iterate over strings. Let's try this in a new file. Open the file string_loop.py from the file explorer and add this code:

## Define a string
message = "Hello"

## Iterate over each character in the 'message' string
for char in message:
  ## Print each character
  print(char)

Save the file and run it from the terminal:

python string_loop.py

The output will be:

H
e
l
l
o

This demonstrates that a for loop can process any sequence, treating a string as a sequence of characters.

Use the range() Function with For Loops

The range() function is a powerful tool often used with for loops to generate a sequence of numbers. This is useful when you need to repeat an action a specific number of times.

The range() function can be used in three ways:

  • range(stop): Generates numbers from 0 up to, but not including, stop.
  • range(start, stop): Generates numbers from start up to, but not including, stop.
  • range(start, stop, step): Generates numbers from start to stop with an increment of step.

Let's see how this works. Open the file range_example.py from the file explorer and add the following code:

## Use range(stop) to print numbers from 0 to 4
print("Numbers from 0 to 4:")
for i in range(5):
  print(i)

print("\n" + "="*20 + "\n") ## A separator for clarity

## Use range(start, stop) to print numbers from 2 to 5
print("Numbers from 2 to 5:")
for i in range(2, 6):
  print(i)

print("\n" + "="*20 + "\n") ## A separator for clarity

## Use range(start, stop, step) to print odd numbers from 1 to 9
print("Odd numbers from 1 to 9:")
for i in range(1, 10, 2):
  print(i)

Save the file and run it from the terminal:

python range_example.py

You should see the following output:

Numbers from 0 to 4:
0
1
2
3
4

====================

Numbers from 2 to 5:
2
3
4
5

====================

Odd numbers from 1 to 9:
1
3
5
7
9

Notice that the stop value is never included in the sequence. If you need to perform an action a fixed number of times but do not need the counter value, you can use an underscore _ as the variable name. This is a common convention in Python.

## This loop will execute 5 times
for _ in range(5):
  print("Hello")

Introduce While Loops

In this step, you will learn about the while loop. Unlike a for loop that iterates a fixed number of times, a while loop continues to execute as long as a specified condition remains True.

The basic syntax of a while loop is:

while condition:
  ## Code to execute
  ## IMPORTANT: Update a variable to eventually make the condition False

It is crucial to ensure the condition will eventually become false. Otherwise, you will create an infinite loop, which will cause your program to run forever.

Let's create a script that uses a while loop to print numbers from 1 to 5. Open the file while_loop_example.py and add the following code:

## Initialize a counter variable
count = 1

## The loop continues as long as 'count' is less than or equal to 5
while count <= 5:
  ## Print the current value of count
  print(count)
  ## Increment count by 1. This is essential to prevent an infinite loop.
  count = count + 1 ## This can also be written as count += 1

Save the file and run it from the terminal:

python while_loop_example.py

You should see the following output:

1
2
3
4
5

Here is how the loop works:

  1. count is initialized to 1.
  2. The condition count <= 5 is checked. 1 <= 5 is True, so the loop body executes.
  3. 1 is printed, and count is incremented to 2.
  4. The condition is checked again. 2 <= 5 is True, so the loop continues.
  5. This process repeats until count becomes 6.
  6. When count is 6, the condition 6 <= 5 is False, and the loop terminates.

Use for loops when you know the number of iterations in advance. Use while loops when repetition depends on a condition that can change during execution.

Control Loop Flow with break and continue

Python provides two statements, break and continue, to alter the normal flow of a loop.

The break statement immediately terminates the loop it is in. Execution continues at the first statement after the loop.

Let's see an example. Open the file break_example.py and add this code, which stops a loop when a certain condition is met:

## Iterate through numbers from 0 to 9
for i in range(10):
  ## If i is 5, the 'if' condition becomes True
  if i == 5:
    print(f"Breaking loop at i = {i}")
    ## The break statement exits the loop immediately
    break
  print(i)

print("Loop finished.")

Save the file and run it:

python break_example.py

The output will be:

0
1
2
3
4
Breaking loop at i = 5
Loop finished.

The loop stopped when i became 5, and the numbers 5 through 9 were never printed.

The continue statement skips the rest of the current iteration and proceeds to the next one.

Let's see how continue can be used to skip printing a specific number. Open the file continue_example.py and add the following code:

## Initialize a counter
count = 0

## Loop while count is less than 10
while count < 10:
  count += 1
  ## If count is 5, the 'if' condition becomes True
  if count == 5:
    print(f"Skipping iteration at count = {count}")
    ## The continue statement skips the rest of this iteration
    continue
  ## This line is skipped when count is 5
  print(count)

print("Loop finished.")

Save the file and run it:

python continue_example.py

The output will be:

1
2
3
4
Skipping iteration at count = 5
6
7
8
9
10
Loop finished.

In this case, when count was 5, the continue statement was executed. This caused the print(count) line to be skipped for that iteration, and the loop moved on to the next iteration where count became 6.

Summary

In this lab, you have learned the fundamentals of loops in Python. You started with the for loop, using it to iterate over sequences like lists and strings. You then explored the range() function to create numeric sequences for for loops.

Next, you were introduced to the while loop for creating loops that run as long as a condition is true. Finally, you learned how to control loop execution with the break statement to exit a loop early and the continue statement to skip an iteration. These concepts are foundational for writing efficient and powerful Python programs.