Practical while Loop: How to Implement Counting with while Loop in Python?

Review of while Loop Basics

In Python, a while loop is a “conditional loop”—it repeatedly executes the code in the loop body as long as the loop condition is True, and stops when the condition becomes False. Its basic syntax is:

while condition:
    # Loop body: code executed when the condition is true
    operation1
    operation2
    ...

For example, to make the computer print “Hello” repeatedly:

count = 0
while count < 3:  # Condition: execute while count is less than 3
    print("Hello")
    count = count + 1  # Increment count after each iteration to avoid infinite loop

Using while Loops for Basic Counting

Counting is one of the most common applications of while loops. The core idea is: use a variable (counter) to track the current number, and update the counter in each iteration until the target value is reached.

Example 1: Count from 0 to 5 (Forward Counting)

To count from 0 to 5 and print each number, follow these steps:

  1. Initialize the counter: count = 0 (starting number)
  2. Set the loop condition: count < 6 (stop when count reaches 6, since we want to include 5)
  3. Loop body operation: Print the current number and update the counter (count += 1)

Code implementation:

count = 0  # Initialize counter to 0
while count < 6:  # Condition: continue while count is less than 6
    print(f"Current number: {count}")  # Print current count
    count += 1  # Increment counter to avoid infinite loop

Output:

Current number: 0
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

Example 2: Count from 5 to 0 (Backward Counting)

To count backward from 5 to 0, simply adjust the counter update (decrement instead of increment):

count = 5  # Initialize to 5
while count >= 0:  # Condition: continue while count is greater than or equal to 0
    print(f"Countdown: {count}")
    count -= 1  # Decrement counter by 1 each iteration

Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Countdown: 0

Advanced: Counting with Calculations

Beyond printing numbers, while loops can combine counting with more complex tasks, such as summing values.

Example 3: Calculate the Sum from 1 to 10

To compute the sum of 1+2+3+…+10, follow these steps:

  1. Initialize the total variable: total = 0 (for accumulating the sum)
  2. Initialize the counter: count = 1 (start from 1)
  3. Loop condition: count <= 10 (stop after reaching 10)
  4. Loop body operation: Add the current number to the total and update the counter

Code implementation:

total = 0  # Initialize total to 0
count = 1  # Start counting from 1

while count <= 10:
    total += count  # Add current count to total (equivalent to total = total + count)
    count += 1      # Increment counter for the next iteration

print(f"The sum from 1 to 10 is: {total}")  # Output: 55

Note: Avoid Infinite Loops!

The most common mistake with while loops is forgetting to update the counter, which keeps the condition always True and causes the program to freeze (infinite loop).

For example, this code will loop infinitely:

count = 0
while count < 5:  # Condition: count < 5
    print(count)
    # Error: Missing count +=1, so count remains 0 forever

Solution: Always include a statement to update the counter (e.g., count +=1 or count -=1) in the loop body to ensure the condition eventually becomes False.

Exercises

Try using while loops to complete these tasks:
1. Count from 1 to 20 and print each number.
2. Calculate the sum of even numbers from 1 to 100 (i.e., 2+4+6+…+100).

Summary

The core steps for using while loops to count are:
- Define the goal: Determine the starting and ending numbers (forward/backward).
- Initialize variables: Define the counter (e.g., count) and any necessary accumulators (e.g., total).
- Set the condition: Ensure the loop condition will become False after a finite number of iterations (to avoid infinite loops).
- Update the counter: Use count +=1 or count -=1 in the loop body to drive the loop toward termination.

With these steps, you can flexibly use while loops to handle various counting scenarios!

Xiaoye