single
Infinite Generators
Scorri per mostrare il 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:
1234567891011def 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
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():
12345678910def counter(): count = 1 while True: yield count count += 1 gen = counter() for _ in range(5): print(next(gen)) # 1, 2, 3, 4, 5
Never iterate over an infinite generator with a plain for loop without a stopping condition – it will run forever and crash your program.
Scorri per iniziare a programmare
Generate unique user IDs using an infinite generator function. The id_generator() function should continuously produce identifiers like "ID_1", "ID_2", etc.
- Initialize the variable
countwith the value 1, as identifiers start from 1. - Use an infinite
whileloop to continuously generate identifiers. - Use
yieldto return the current identifier in the formatf"ID_{count}". - Increment
countby 1 after each iteration. - Initialize the generator object
id_genby callingid_generator().
Soluzione
Grazie per i tuoi commenti!
single
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione