2012-12-17 45 views
2

可能重複:
Python Infinity - Any caveats?
python unbounded xrange()印刷號,其中x是無窮大蟒蛇

我有一個關於Python這樣的問題,你編寫一個簡單的腳本,打印數字序列從1到x其中x是無窮大。 這意味着,「x」可以是任何值。例如,如果我們要打印一個數字序列,它將從1打印數字到一個「if」語句,即在數字「10」處停止並且打印過程將停止。

在我當前的代碼,我使用的是「for」循環是這樣的:

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

我試圖找出如何「100」中的「範圍」可以用別的東西代替會讓循環連續不斷地繼續打印序列,而無需指定值。 任何幫助,將不勝感激。由於

+1

使用while循環 –

+2

@Hedde我不明白它是如何的重複或給其他的問題,甚至幫助。 –

回答

14

隨着itertools.count

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

用一個簡單的循環while

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

非常感謝。這就像魅力一樣。 –

+1

@MaxWayne我很高興它有幫助。那麼你可能想[接受答案](http://meta.stackexchange.com/a/5235/181223)。 –

2

y可以是一個數字。

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

你不能有y無限大或負。下面的例子會對我有用。

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

我試過了,但是出現了一個錯誤提示:「y沒有定義」 感謝您的幫助 –

+0

python「integer」可以變得多大沒有限制 - 它會默默地轉換爲「long」並繼續下去,直到你用完內存。 – mgilson

+0

@mgilson:我改正了答案。我說python限制..這是內存不足......我不認爲我的答案誤導。謝謝 –

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

我相信你想在'while'循環中遞增。我已經把它放在那裏。我還將'While'改爲'while'以使其成爲有效的語法。 – mgilson

+0

@mgilson對不起,錯字 –

+0

'x = x + 1'應該是'x + = 1' –

2

你可以用發電機做到這一點:

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

for x in infinity(1): 
    print x