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.
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.
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.
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.
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!
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:
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 ....
This is a bit smaller code than what the other user provided!
x = 1
while True:
x = x+1
print x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With