Counting in a While loop in Python

avatar

Borislav Hadzhiev

Last updated: Sep 21, 2022

banner

Photo from Unsplash

Counting in a While loop in Python #

To count in a while loop:

  1. Declare a count variable and set it to 0.
  2. Use a while loop to iterate as long as count is less than N.
  3. On each iteration, increment the value of the count variable by 1.
main.py
count = 0 max_count = 5 while count < max_count: count += 1 print(count) # 👉️ 1 2 3 4 5

We declared a count variable and set it to 0.

The max_count variable is used in the condition of the while loop.

The while loop keeps iterating until the value of count is equal to or greater than the value of max_count.

On each iteration, we increment the value of the count variable by 1 to move towards the case where the condition is no longer met.

You can also use this approach to count how many times a while loop runs.

main.py
count = 0 my_list = ['bobby', 'hadz', 'com'] while len(my_list) > 0: my_list.pop() count += 1 print(count) # 👉️ 1 2 3 print(count) # 👉️ 3

On each iteration of the while loop, we increment the count variable and remove an item from a list.

The while loop keeps iterating and counting until the list is empty.

The += operator is a shorthand for count = count + 1.

The following code sample achieves the same result using the more verbose syntax.

main.py
count = 0 my_list = ['bobby', 'hadz', 'com'] while len(my_list) > 0: my_list.pop() count = count + 1 print(count) # 👉️ 1 2 3 print(count) # 👉️ 3

If you don't have a condition and only need to iterate N times and keep track of the count, you can also use the range() class.

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1.

If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.

main.py
result = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(result)

The range() class is more intuitive to use if you know how many times you need to iterate in advance.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.