0
0
Pythonprogramming~5 mins

Counter-based while loop in Python

Choose your learning style9 modes available
Introduction

A counter-based while loop helps you repeat actions a set number of times by counting each step.

When you want to repeat a task exactly 5 times.
When you need to process items one by one and count how many you have done.
When you want to keep doing something until a number reaches a limit.
When you want to print numbers from 1 to 10.
When you want to ask a user for input 3 times.
Syntax
Python
counter = 0
while counter < limit:
    # do something
    counter += 1

The counter starts at a number, usually 0 or 1.

Inside the loop, increase the counter to avoid an endless loop.

Examples
This prints numbers 1 to 5 using a counter starting at 1.
Python
count = 1
while count <= 5:
    print(count)
    count += 1
This prints 'Hello' three times by counting from 0 to 2.
Python
i = 0
while i < 3:
    print('Hello')
    i += 1
Sample Program

This program counts from 1 to 5 and prints each step.

Python
counter = 1
while counter <= 5:
    print(f"Step {counter}")
    counter += 1
OutputSuccess
Important Notes

Always update the counter inside the loop to avoid infinite loops.

You can start counting from any number, not just zero.

Use a while loop when you want more control over the counting process.

Summary

A counter-based while loop repeats actions a set number of times.

Start a counter, check it in the loop condition, and increase it each time.

This helps you do tasks like printing numbers or repeating messages easily.