from itertools import islice
def counter(low, high, step):
current = low
while current <= high:
yield current
current += step
# 每次循环一个值,按需生成
for number in counter(3, 9, 2):
print(f"{number = }")
# 没有结束条件:它自己永远不会结束
def powers_of_two():
current = 1
while True:
yield current
current *= 2
# islice 截取无限生成器
first_five = list(islice(powers_of_two(), 5))
# first_five is [1, 2, 4, 8, 16]
print(f"{first_five = }")