7  Control Structures: Loops

Loops are one of the most powerful features in programming, enabling the repeated execution of a block of code. This repetition is often necessary for tasks such as processing elements in a collection, generating sequences of values, and executing complex algorithms. Understanding loops is essential for developing efficient and concise programs, as they reduce redundancy and simplify code that would otherwise require numerous repetitive statements.

Why Use Loops?

Loops are used to automate repetitive tasks, making code more efficient and easier to manage. Here are some key reasons to use loops:

  1. Reducing Code Duplication: Without loops, you would need to write repetitive code multiple times. Loops allow you to write a block of code once and execute it multiple times.
  2. Dynamic Execution: Loops can handle dynamic and varying data sizes. For instance, processing user input or reading data from a file where the number of elements is unknown beforehand.
  3. Complex Calculations: Many algorithms, such as those used in searching and sorting, rely on loops to iterate through data and perform calculations.

Types of Loops in Python

Python supports two primary types of loops:

  1. while Loop: Executes a block of code as long as a specified condition is True. The condition is checked before each iteration.
  2. for Loop: Iterates over a sequence and executes a block of code for each item in the sequence.

7.1 The while Loop

The while loop is one of the fundamental control structures in Python, allowing the repeated execution of a block of code as long as a specified condition is True. This type of loop is particularly useful when the number of iterations is not known beforehand and depends on dynamic conditions during runtime.

Basic Syntax

The basic syntax of a while loop is:

while condition:
    statement(s)
  • condition: An expression that evaluates to True or False.
  • statement(s): The block of code that will be executed repeatedly as long as the condition is True.

Example: Simple while Loop

Consider a simple example where we print numbers from 1 to 5:

i = 1
while i <= 5:
    print(i)
    i += 1
1
2
3
4
5

In this example, the variable i is initialized to 1. The while loop checks if i is less than or equal to 5. If the condition is True, it prints the value of i and increments i by 1. The loop continues until i becomes greater than 5.

Infinite Loops

A common pitfall with while loops is the creation of infinite loops, which occur when the loop’s condition never becomes False. This can cause the program to run indefinitely, potentially causing it to become unresponsive.

Example of an infinite loop:

while True:
    print("This loop will run forever.")

To prevent infinite loops, ensure that the loop’s condition will eventually become False.

while Loop with Else Clause

Python allows an optional else clause with while loops. The else block is executed when the loop condition becomes False.

Example:

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print("Loop ended naturally.")
1
2
3
4
5
Loop ended naturally.

In this example, the else block is executed after the while loop finishes executing, printing “Loop ended naturally.”

Nested while Loops

while loops can be nested within other loops to handle more complex tasks, such as iterating over multi-dimensional data structures.

Example:

i = 1
while i <= 3:
    j = 1
    while j <= 3:
        print(j)
        j += 1
    i += 1

In this example, the outer while loop iterates over the variable i from 1 to 3, and for each iteration, the inner while loop iterates over the variable j from 1 to 3.

Controlling Loop Execution

Python provides several statements to control the execution of while loops:

  • break: Terminates the loop prematurely.
  • continue: Skips the rest of the loop body for the current iteration and proceeds to the next iteration.
  • pass: Does nothing and is used as a placeholder in loops or functions where code will be added later.

Examples:

  1. Using break:

    i = 1
    while i <= 10:
        if i == 5:
            break
        print(i)
        i += 1
    1
    2
    3
    4
  2. Using continue:

    i = 1
    while i <= 10:
        if i % 2 == 0:
            i += 1
            continue
        print(i)
        i += 1
    1
    3
    5
    7
    9
  3. Using pass:

    i = 1
    while i <= 10:
        if i % 2 == 0:
            pass  # Placeholder for future code
        else:
            print(i)
        i += 1
    1
    3
    5
    7
    9

7.2 The for Loop

The for loop in Python is used for iterating over a sequence. Unlike the while loop, the for loop is preferred for its simplicity and readability when working with sequences. It provides a straightforward way to traverse elements in a collection, making it easier to write and understand.

Basic Syntax

The basic syntax of a for loop is:

for variable in sequence:
    statement(s)
  • variable: A variable that takes the value of each item in the sequence during iteration.
  • sequence: A collection of items to iterate over (e.g., list, tuple, string, range).
  • statement(s): The block of code that will be executed for each item in the sequence.

Example: Iterating Over a List

Consider an example where we iterate over a list of numbers and print each number:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)
1
2
3
4
5

In this example, the for loop iterates over the list numbers, and the variable num takes the value of each item in the list during each iteration.

The range() Function

The range() function generates a sequence of numbers, which is particularly useful for creating loops that run a specific number of times. The range() function can take up to three arguments: start, stop, and step.

  • start: The starting value of the sequence (inclusive). Default is 0.
  • stop: The ending value of the sequence (exclusive).
  • step: The difference between each pair of consecutive values. Default is 1.

Example using range():

for i in range(1, 6):
    print(i)
1
2
3
4
5

This loop prints numbers from 1 to 5. The range(1, 6) function generates the numbers 1, 2, 3, 4, and 5.

Iterating Over Strings

Strings are sequences of characters, and you can use a for loop to iterate over each character in a string.

Example:

message = "Hello, World!"
for char in message:
    print(char)
H
e
l
l
o
,
 
W
o
r
l
d
!

In this example, the for loop iterates over the string message, and the variable char takes the value of each character in the string during each iteration.

Loop Control Statements

As with while loops, Python provides several statements to control the execution of for loops:

  • break: Terminates the loop prematurely.
  • continue: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
  • pass: Does nothing and is used as a placeholder in loops or functions where code will be added later.

Examples:

  1. Using break:

    for i in range(1, 10):
        if i == 5:
            break
        print(i)
    1
    2
    3
    4
  2. Using continue:

    for i in range(1, 10):
        if i % 2 == 0:
            continue
        print(i)
    1
    3
    5
    7
    9
  3. Using pass:

    for i in range(1, 10):
        if i % 2 == 0:
            pass  # Placeholder for future code
        else:
            print(i)
    1
    3
    5
    7
    9

Practical Applications

for loops are used in a wide range of practical applications, from data processing to generating patterns. Here are some examples:

Example: Summing Numbers in a List

Calculate the sum of all numbers in a list:

numbers = [23, 45, 12, 89, 34]
total = 0

for num in numbers:
    total += num

print("Sum:", total)
Sum: 203

In this example, the for loop iterates over the list numbers, adding each number to the variable total, which holds the sum.

Example: Finding the Maximum Value

Find the maximum value in a list:

numbers = [23, 45, 12, 89, 34]
max_value = numbers[0]

for num in numbers:
    if num > max_value:
        max_value = num

print("Maximum value:", max_value)
Maximum value: 89

In this example, the for loop iterates over the list numbers, updating the variable max_value if a larger number is found.

7.3 Exercises

Exercise 1: Counting Down

Write a program that counts down from 10 to 1 using a while loop.

Exercise 2: Sum of Positive Numbers

Write a program that repeatedly asks the user for a number until they enter a negative number. The program should then print the sum of all positive numbers entered.

input()

The input() function is used to display the given string to the console and wait for user input. The value entered by the user will be a string. Thus, the input must be converted to an int if an integer is needed in the rest of the code.

For this exercise, you can get the user input with the command

num = int(input("Enter a number (negative number to stop): "))

Exercise 3: Factorial Calculation

Write a program to calculate the factorial of a number using a while loop. Print the end result. Use an input() function as in Exercise 2.

Exercise 4: Guess the Number

Write a number guessing game where the program generates a random number between 1 and 100, and the user has to guess it. The program should give hints if the guess is too high or too low and keep asking until the user guesses correctly.

Use the following code to generate the random number:

import random
number = random.randint(1, 100)

Exercise 5: Sum of Even Numbers

Write a program to calculate the sum of all even numbers between 1 and 50.

Exercise 6: Prime Numbers

Write a program to print all prime numbers between 1 and 50 using a for loop and conditional statements.