0

By "counter" I mean the "i" in the code I attached. I just picked up Python for University, and I was wondering if i could maniuplate the counter just like you can in C++

n=5
for i in range(n):
    print("Test")
    i=i-1

The result of this code is

Test Test Test Test Test

but i was wondering if you could manipulate the "i" so it is an infinite loop

Feel free to ask questions about what I mean if it is not clear enough

  • What do you really want to happen? Surely you don't want to have an infinite loop, right? You are not really using `i`. A better example could help understanding your question. – trincot Jan 27 '22 at 20:58
  • If you want an infinite loop, you may consider using something like `while True` – Kureteiyu Jan 27 '22 at 21:02

1 Answers1

2

The problem is that python uses iterators, which aren't meant to be manipulated while getting iterated. A good rule is, if you need to manipulate a for loop, you shouldn't use a for loop. The better way would be, using a while loop. An example:

n = 10
while n > 5:
    print("Test " + n)
    n -= 2
    if n == 6:
        n += 1

Or the infinite loop:

while True:
    print("Test")

Take a look at this for more information.

Frederick
  • 450
  • 4
  • 22