3

Possible Duplicate:
Python Infinity - Any caveats?
python unbounded xrange()

I have a question regarding Python where you code a simple script that prints a sequence of numbers from 1 to x where x is infinity. That means, "x" can be any value.

For example, if we were to print a sequence of numbers, it would print numbers from 1 to an "if " statement that says stop at number "10" and the printing process will stop.

In my current code, I'm using a "for" loop like this:

for x in range(0,100):
    print x

I'm trying to figure how can "100" in "range" be replaced with something else that will let the loop keep on printing sequences continuously without specifying a value. Any help would be appreciated. Thanks

Community
  • 1
  • 1
Max Wayne
  • 113
  • 1
  • 2
  • 10

4 Answers4

14

With itertools.count:

import itertools
for x in itertools.count():
    print x

With a simple while loop:

x = 0
while True:
    print x
    x += 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
2

y can be a number.

for x in range(0,y):
    print x

you can't have y infinitely large or negative. Following example will be useful I think.

>>> for y in range(0,):
...     print y
... 
>>> 
>>> for y in range(0,1000000000000000):
...     print y
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: range() result has too many items
>>> for y in range(0,-1):
...     print y
... 
>>>
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
2

You could do it with a generator:

def infinity(start=0):
    x = start
    while True:
        yield x
        x += 1

for x in infinity(1):
    print x
martineau
  • 119,623
  • 25
  • 170
  • 301
0
x=0
while True:
  print x
  x = x +1
mgilson
  • 300,191
  • 65
  • 633
  • 696
Jimmy Kane
  • 16,223
  • 11
  • 86
  • 117