Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Infinite Generators | Especificação do Valor de Retorno da Função
Tutorial de Funções em Python
Seção 4. Capítulo 5
single

single

bookInfinite Generators

Deslize para mostrar o menu

Recall that yield pauses a generator and resumes it on the next next() call. So far, the generators you have seen had a clear stopping point. But generators become especially powerful when combined with an infinite loop – producing values indefinitely without ever storing them in memory.

Infinite Generators with while True

Using a while True loop inside a generator creates an infinite sequence – something that would be impossible to store as a list. The generator only produces the next value when next() is called:

1234567891011
def counter(): count = 1 while True: # Runs forever yield count # Return current value and pause count += 1 # Resume from here on the next call gen = counter() print(next(gen)) # 1 print(next(gen)) # 2 print(next(gen)) # 3
copy

No matter how many times you call next(), the generator will always have a new value ready – it never runs ahead or stores values in memory.

Controlling an Infinite Generator

Since the generator runs forever, you need to control how many values you retrieve. The most common way is using a for loop with range():

12345678910
def counter(): count = 1 while True: yield count count += 1 gen = counter() for _ in range(5): print(next(gen)) # 1, 2, 3, 4, 5
copy
Note
Note

Never iterate over an infinite generator with a plain for loop without a stopping condition – it will run forever and crash your program.

Tarefa

Deslize para começar a programar

Generate unique user IDs using an infinite generator function. The id_generator() function should continuously produce identifiers like "ID_1", "ID_2", etc.

  1. Initialize the variable count with the value 1, as identifiers start from 1.
  2. Use an infinite while loop to continuously generate identifiers.
  3. Use yield to return the current identifier in the format f"ID_{count}".
  4. Increment count by 1 after each iteration.
  5. Initialize the generator object id_gen by calling id_generator().

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 5
single

single

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt