Easy Way To Keep Counting Up Infinitely
What's a good way to keep counting up infinitely? I'm trying to write a condition that will keep going until there's no value in a database, so it's going to iterate from 0, up to
Solution 1:
Take a look at itertools.count().
From the docs:
count(start=0, step=1)
--> count objectMake an iterator that returns evenly spaced values starting with
n
. Equivalent to:
defcount(start=0, step=1):
# count(10) --> 10 11 12 13 14 ...# count(2.5, 0.5) -> 2.5 3.0 3.5 ...
n = start
whileTrue:
yield n
n += step
So for example:
import itertools
for i in itertools.count(13):
print(i)
would generate an infinite sequence starting with 13, in steps of +1. And, I hadn't tried this before, but you can count down too of course:
for i in itertools.count(100, -5):
print(i)
starts at 100, and keeps subtracting 5 for each new value ....
Solution 2:
This is a bit smaller code than what the other user provided!
x = 1whileTrue:
x = x+1print x
Solution 3:
A little shorter, using an iterator and no library:
x = 0for x initer(lambda: x+1, -1):
print(x)
But it requires a variable in the current scope.
Post a Comment for "Easy Way To Keep Counting Up Infinitely"