6.3 While loop

The while loop in Python is used to repeatedly execute a block of code as long as a specified condition is true. This means that the loop will continue to run until the condition evaluates to False.

Syntax:

The basic syntax of a while loop is:

while condition:
    # Code to execute

  • condition - This is a boolean expression that is evaluated before each iteration of the loop. If the condition is True, the loop body is executed. If the condition is False, the loop terminates, and the program continues with the next statement after the loop.

  • loop body - The block of code that you want to repeat. This block must be indented to indicate that it is part of the loop.

 

Example 6.3.1 - Let’s look at a simple example where we count from 1 to 5 using a while loop.

count = 1  # Initialize the counter variable

while count <= 5:  # Condition to continue the loop
    print(count)  # Print the current value of the counter
    count += 1  # Increment the counter by 1

Example 6.3.1 - Explanation

  1. Initialization - The counter variable count is initialized to 1.
  2. Condition - The loop condition is count <= 5. As long as count is less than or equal to 5, the loop will continue to run.
  3. Loop Body - Inside the loop, the current value of count is printed, and then count is incremented by 1 using count += 1.

 

Example 6.3.2 - This will print numbers from 0 to 4, similar to the output that we saw in 6.2. for-in [loop example].

i = 0
while i < 5:
    print(i)
    i += 1

Example 6.3.2 - Output

0
1
2
3
4

 

Example 6.3.3 - Another example using a while loop to sum up numbers.

total = 0
number = 1
while number <= 10:
    total += number
    number += 1
print(total)

Example 6.3.3 - Output

55

 

Example 6.3.4 - In this example we shall calculate the sum of all even numbers from 1 to a positive integer entered by the user. The program is using a while loop to iterate through the numbers and determine the sum. Finally, the program will print the sum of the even numbers.

# Ask the user to enter a positive integer
number = int(input("Enter a positive integer: "))

# Initialize a counter variable
count = 1

# Initialize a variable to hold the sum of even numbers
sum_of_evens = 0

# Use a while loop to iterate through numbers from 1 to the entered number
while count <= number:
    # Check if the current number is even
    if count % 2 == 0:
        # Add the even number to the sum
        sum_of_evens += count
    # Increment the counter variable
    count += 1

# Print the sum of even numbers
print(f"The sum of all even numbers from 1 to {number} is {sum_of_evens}.")
Example 6.3.4 - Output

If the user enters 10, the program should output:

The sum of all even numbers from 1 to 10 is 30.

Example 6.3.4 - Explanation

  1. Input - The user is prompted to enter a positive integer, which is stored in the variable number.

  2. Initialization - Two variables are initialized:

    • count is set to 1 to start counting from the first number.
    • sum_of_evens is set to 0 to accumulate the sum of even numbers.
  3. While loop

    • The loop runs as long as countis less than or equal to number.
    • Within the loop, the code checks if count is even using the modulus operator (count % 2 == 0). If it is even, it adds count to sum_of_evens.
    • The counter count is incremented by 1 after each iteration.
  4. Output - After the loop completes, the program prints the sum of all even numbers from 1 to the entered number.

 


 

Exercise 6.3.1 - Write a Python program that asks the user to enter a positive integer and then prints out all the numbers from 1 up to and including that number. Use a while loop to accomplish this.

Exercise 6.3.1 - Model Answer - Make sure to work out the exercise before checking the model answer.