An easy way to count endlessly

What a good way to keep counting endlessly? I am trying to write a condition that will continue until there is no value in the database, so it will go from 0 to theoretically infinity (of course, inside the try block).

How would I count up endlessly? Or should I use something else?

I am looking for something similar to i ++ in other languages, where it continues iterating until it fails.

+5
source share
3 answers

Take a look at itertools.count () .

From the docs:

count(start=0, step=1) → counting object

Make an iterator that returns evenly spaced values, starting at n. Equivalent to:

def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step

So for example:

import itertools

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

, 13, +1. , :

for i in itertools.count(100, -5):
    print(i)

100 5 ....


+19

, , !

x = 1
while True:
    x = x+1
    print x
+1

xrangewill provide you with an iterable object that will not use memory during repeat, the cycle foris cleaner than the dial whileif you ask me.

import sys
for i in xrange(0,sys.maxint):
   print i
0
source

All Articles