Home > Mobile >  Can I make a for loop go forever? (Python)
Can I make a for loop go forever? (Python)

Time:11-17

If I have code like this:

for i in range(3):
    print("Hello")

Is there a way to make it print forever with a for loop?

CodePudding user response:

You can use something like itertools.count:

from itertools import count

for i in count():
    print(i)

CodePudding user response:

Is there any reason it needs to be a for loop?

You could just use a while loop,

while True:
    print('hello')

To stop it press Ctrl c on your keyboard.

CodePudding user response:

If your for loop takes its data from a generator that runs forever, sure:

def infinite():
    while True:
        yield


for __ in infinite():
    print("Hello")

You asked if it could be done as a one-liner. Not like this, but with some trickery (and without cheating by just importing it from elsewhere like itertools):

for __ in iter(int, 1):
    print("Hello")

This works because int() will just return 0 endlessly, never reaching the sentinel value of 1. I still feel it's cheating a bit though, you'd only ever do this to make the point that it can be done with for - obviously while True: is the way to go if you seriously need this.

  • Related