Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to keep counting up infinitely

Tags:

python

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 theoretically infinity (inside a try block, of course).

How would I count upwards infinitely? Or should I use something else?

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

like image 688
Steven Matthews Avatar asked Jul 11 '12 02:07

Steven Matthews


People also ask

How do you make a loop that runs forever?

The infinite loop We can create an infinite loop using while statement. If the condition of while loop is always True , we get an infinite loop.

How do you count to infinity in Python?

As of 2020, there is no such way to represent infinity as an integer in any programming language so far. But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float('inf') as an integer to represent it as infinity.

How do you count +1 in Python?

just start your count at 1, change your check statement to check if the number is less than 100, and use "count = count + 1" Should work, good luck! Save this answer.

How do you do a count loop in Python?

Use the enumerate() function to count in a for loop, e.g. for index, item in enumerate(my_list): . The function takes an iterable and returns an object containing tuples, where the first element is the index, and the second - the item. Copied!


2 Answers

Take a look at itertools.count().

From the docs:

count(start=0, step=1) --> count object

Make an iterator that returns evenly spaced values starting with 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)

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 ....


like image 133
Levon Avatar answered Oct 20 '22 00:10

Levon


This is a bit smaller code than what the other user provided!

x = 1
while True:
    x = x+1
    print x
like image 34
paebak Avatar answered Oct 19 '22 23:10

paebak