The standard library's itertools provide an iterator counting up:

import itertools

for i in itertools.count():
    print(i)

You can set the start and step:

# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) --> 2.5 3.0 3.5 ...
Answer from rassi on Stack Overflow
🌐
Pierian Training
pieriantraining.com › home › counting in a python loop: a beginner’s guide
Counting in a Python Loop: A Beginner's Guide - Pierian Training
April 28, 2023 - We then use a while loop to check if the counter variable is greater than zero, and if it is, we print out its value and decrement it by one.
Discussions

How to exit while loops (using counters)
for i in range(len(lst)): ...some operation... ...some operation... if Y criteria met: count += 1 count can theoretically be incremented on every pass through the "for i in" loop. As already suggested, return from a function http://www.tutorialspoint.com/python/python_functions.htm def function(lst): count = 0 while True: for i in range(len(lst)): ...some operation... ...some operation... if Y criteria met: count += 1 if count > 100: return Don't use i, l, or O as single digit variable names as they can look like numbers. More on reddit.com
🌐 r/learnpython
10
1
June 16, 2024
Help Understanding While loops
It has been a good source for me. I have made it to this point once and I restarted the course again. I am stuck at loops again. This seems to be an important part. If anyone could help me understand what is happening in this line of code I would appreciate it. counter = 0 while counter More on discuss.python.org
🌐 discuss.python.org
5
0
November 3, 2023
Can you count the number of times a loop occurs?
Define a variable "counter" with value 0 before the loop. Before the end of each loop, increase the counter value by 1 ( counter = counter + 1). More on reddit.com
🌐 r/learnpython
6
4
February 7, 2021
python - While loop counter - Stack Overflow
Using VS2015 Python 3.4 Having some issues with this while counter. It is slowly driving me insane as I'm sure it 'should' work but isn't updating the counter. I've ran stepping debug and can see the More on stackoverflow.com
🌐 stackoverflow.com
December 28, 2015
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 5-1-while-loop
5.1 While loop - Introduction to Python Programming | OpenStax
March 13, 2024 - # Initialization counter = 1 # While loop condition while counter <= 10: if counter % 2 == 1: print(counter) # Counting up and increasing counter's value by 1 in each iteration counter += 1
🌐
Pythonclassroom
pythonclassroom.com › loops › while-loop-count-up
while loop - count up | Python Classroom
December 9, 2019 - The placement of x = x + 1 in the while loop matters. If you print x after x = x + 1, the value will be different than if you printed it before. Using a while loop, print odd numbers from 1 to 99.
🌐
Reddit
reddit.com › r/learnpython › how to exit while loops (using counters)
r/learnpython on Reddit: How to exit while loops (using counters)
June 16, 2024 -

Technically this might be a 'learning to code' question but my language of choice happens to be Python so here goes!

I've come across this problem a few times while working through Daniel Zingaro's 'Learning to code' book (n00b here). Basically, I've got a while loop that is set to end if my counter reaches X number.

However, when I nest a for loop in that, with a list of say 3 elements (index 0,1,2) and add the counter at the end of each loop, my while loop statement is only being checked every three for loop iterations.

What follows is that my counter will over shoot by a few numbers because even though I've satisfied the while loop, the for loop operation needs to run until the end.

Is there a good way to force the while loop to end at the desired counter number without invoking the 'break' operation? The book warns that using 'break' can sometimes be bad practice, as it won't always clear why it's in the code. I get it's probably necessary sometimes but if I can avoid it, I'd like to learn how it can be done.

I've typed out an example snippet in case my description is unclear. In this case, the for loop runs through a list of 3 letters.

lst = ['A','B','C']
count = 0
while count <= 100:
    for i in range(len(lst)):
        ...some operation...
        ...some operation...
        if Y criteria met:
            count += 1


'count' exits when it equals '102'.

The problem I'm working on is here.

Find elsewhere
🌐
CodeRivers
coderivers.org › blog › while-count-python
Python's `while` Loop: Counting and Beyond — CodeRivers
The counter variable is initialized to 1. The while loop condition counter <= 5 checks if the counter is less than or equal to 5.
🌐
Smash Your Exams
code.smashyourexams.com › learn › learn python › iteration: while loops › counting with a while loop
Counting with a Python while Loop | Counters | GCSE
Work it out, do not run it. ... Change < to <= and run it. Then start count at 5 and check how many lines you get before anything prints. Set the counter before the loop, with count = 1.
🌐
Python.org
discuss.python.org › python help › help understanding while loops
Help Understanding While loops - Python Help - Discussions on Python.org
November 3, 2023 - Hello, I have been learning python using Solo learn. It has been a good source for me. I have made it to this point once and I restarted the course again. I am stuck at loops again. This seems to be an important part. If anyone could help me understand what is happening in this line of code I would appreciate it. counter = 0 while counter
🌐
Reddit
reddit.com › r/learnpython › can you count the number of times a loop occurs?
r/learnpython on Reddit: Can you count the number of times a loop occurs?
February 7, 2021 -

I'm new to python, sorry if my wording is terrible.

I'm building a very basic number guessing game. I don't want to copy and paste the whole code into here unless someone wants it in the comments.

I have it so that you guess a number between 1-100. After each guess it will tell you if it's too low or too high. Once you guess it correct it will say "Correct!". I want it to also tell you how many attempts it took you to find the correct answer and print that out with the "Correct!". How do you do that?

🌐
Quackit
quackit.com › python › tutorial › python_while_loops.cfm
Python While Loops
while loops are often used with a counter — an incrementing (or decrementing) number. Like this: ... The bit where it increments the counter is a crucial part of this loop. If we didn't do that, the loop would continue on forever. The program would get stuck in an infinite loop (not a good thing).
🌐
SQLPad
sqlpad.io › tutorial › python-while-loop
Python while loop | SQLPad
April 29, 2024 - In Python, the while loop enables us to perform a task repeatedly as long as a specified condition remains true. For example, if we want to print out numbers from 1 to 5, we could use a while loop like this: counter = 1 while counter <= 5: ...
🌐
Learn Python
learnpython.dev › 02-introduction-to-python › 110-control-statements-looping › 30-while-loops
while loops :: Learn Python by Nina Zakharenko
Instead of running just once when a condition is met, like an if statement, they run forever until a condition is no longer met. while loops usually need to be accompanied by an always changing sentinel value. >>> counter = 0 >>> max = 4 >>> >>> while counter < max: ...
Top answer
1 of 2
1

counter resets to its original value because it is a global variable. Global variables in Python behave differently than in other languages. Try this snippet :

counter = 3
def f():
    counter = 2 # Shadows global 'counter' by a newly defined one
f()
print (counter) # Prints 3 !

You could expect the printed value to be 2, but is 3 instead. Global variables are immutable by default, and attempt to modify it in a local scope without global keyword will shadow by local definition instead. See this discussion to use global variable although it would be preferable to rework your program to use local variables.

EDIT: There is also a mistake, counter is initialized to 3 and only incremented, so the condition >= 0 will always be satisfied (thus creating an infinite loop). You can try:

[...]
def rps_game(user_obj, ai_obj, counter):
    if counter <= 0:
         return
    print('Player selected %s ' % user_obj)
    print('Computer selected %s ' % ai_obj)
    while user_obj in rps and ai_obj in rps :
    [...]
    else:
        print('Invalid input, please select Rock, Paper or Sissors')
        rps_game(user_obj, ai_obj, counter-1)

rps_game(user_obj, ai_obj, 3)
2 of 2
0

The else containing the counter update is indented so that it hangs off of the while. That means that it executes only when the while loop terminates because the condition is false (not when you break out). In this case, the condition is false when either the user or ai input is not in the list of valid inputs or the counter is negative. The counter can never be negative because it starts at 3 and is only ever incremented. If the user input is invalid, the error message is printed, the counter is incremented, and then you use recursion to call the function with the same arguments. Since the arguments haven't changed, the function should do the same thing it just did, unless it depends on global data (counter). However, if counter is local (initialized inside the function), each invocation of the function gets a fresh copy. If counter is global (initialized outside the function, but declared global inside the function), it still won't work because you need to decrement it. And even then, because none of the other inputs have changed, it will just print the error message over and over.

Your loop bound appears to expect counter to count down from 3 since it keeps going as long as counter is positive. Incidentally, using >= as the conditional will make the loop execute 4 times (3, 2, 1, and 0). You might want to change the conditional to strictly greater than, and change the counter increment to a counter decrement.

Next, you are using recursion (the function calls itself), but this should be unnecessary since the loop gets you back to where you need to be.

Next, the lose cases break out of the loop, but the win cases do not. If you win, the code will loop, not modifying the counter or any of the other inputs, so it will not terminate.

Finally, the user input is read from outside the function, so it never changes inside the loop. If the user enters an illegal value, the loop will just keep testing the same value. You probably want to read the user input inside the loop.

🌐
Alma Better
almabetter.com › bytes › tutorials › python › while-loop-in-python
While Loop in Python
October 2, 2024 - # Initialize counter counter = ... while Loop. The code initializes a counter variable to 0, then prints the counter value and increments the counter by 1 until the counter is no longer less than 10....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-while-loop
Python While Loop - GeeksforGeeks
When the condition becomes false, the line immediately after the loop in the program is executed. Here, the condition for while will be True as long as the counter variable (count) is less than 3.
Published: October 5, 2026
🌐
Snakify
snakify.org › while loop
While loop - Learn Python 3 - Snakify
Here one can replace the "while" loop by the for ... in range(...) loop: ... In this example, the variable i inside the loop iterates from 1 to 10. Such a variable whose value changes with each new loop iteration is called a counter.
🌐
GeeksforGeeks
geeksforgeeks.org › python › loops-in-python
Loops in Python - GeeksforGeeks
cnt = cnt + 1 increases the counter value by 1. Below is the flowchart of While loop: Flowchart of While loop · An infinite while loop runs continuously because its condition always remains true.
Published: September 19, 2026
🌐
Python Course
python-course.eu › python-tutorial › loops.php
19. While Loops | Python Tutorial | python-course.eu
November 8, 2023 - It's best to illustrate the operating principle of a loop with a simple Python example. The following small script calculates the sum of the numbers from 1 to 100. We will later introduce a more elegant way to do it. n = 100 total_sum = 0 counter = 1 while counter <= n: total_sum += counter counter += 1 print("Sum of 1 until " + str(n) + " results in " + str(total_sum))