[英]Can I make a for loop go forever? (Python)
如果我有這樣的代碼:
for i in range(3):
print("Hello")
有沒有辦法讓它用for
循環永遠打印?
如果您的 for 循環從永遠運行的生成器中獲取數據,請確保:
def infinite():
while True:
yield
for __ in infinite():
print("Hello")
你問它是否可以作為單線完成。 不是這樣,但有一些技巧(並且不會通過從其他地方像itertools
導入它來作弊):
for __ in iter(int, 1):
print("Hello")
這是有效的,因為int()
只會無休止地返回0
,永遠不會達到1
的哨兵值。 我還是覺得它欺騙了一下,雖然,你永遠只能這樣做是為了說明一點,這是可以做到for
-很明顯while True:
是去,如果你真的需要這樣的方式。
有什么理由需要 for 循環嗎?
你可以只使用一個while循環,
while True:
print('hello')
要停止它,請按鍵盤上的Ctrl + c 。
你可以使用類似itertools.count
東西:
from itertools import count
for i in count():
print(i)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.