+ 1

Python Generators Question

Why does this code execute?: def infinite_sevens(): while True: yield 7 for i in infinite_sevens(): print(i) If the generator infinite_sevens is changed to while False then there is no output, so something here is considered "True". But when changing yield 7 to yield 0, the code still executes. So what gives??

12th Jan 2024, 8:32 AM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
3 Respostas
+ 3
21kHzBANK21kHZ , The "something" that is considered True is the bool literal True itself. It, True, is occupying the part of the while compound statement that is an expression to be evaluated to a bool value. The expression is also called the condition. Putting the bool literal as the condition guarantees that the expression always evaluates the same way. True always evaluates as True.
12th Jan 2024, 2:52 PM
Rain
Rain - avatar
+ 2
while True results in an infinite loop. The function will yield 7 everytime you call it. changing it to yield 0 will just make it yield infinite 0's. while False kills the loop and it will yield nothing. if you do not put any while loop, the generator will just yield one value and raise an error the next time you call it.
12th Jan 2024, 9:13 AM
Bob_Li
Bob_Li - avatar
+ 1
@Rain I get it! It's like writing "while (True)", which would be the same as writing a true expression such as "while (1 == 1)" or something like that. Thanks!
12th Jan 2024, 4:46 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar