+ 5

How it works?

def is_Even(k): if not k % 2: print(f'{k}-even', end=' ') yield else: print(f'{k}-odd', end=' ') evens = [k for k in range(10) for bar in is_Even(k)] print(f'\n{evens=}') Can you figure out how the preceding produces these results? 0-even 1-odd 2-even 3-odd 4-even 5-odd 6-even 7-odd 8-even 9-odd evens=[0, 2, 4, 6, 8] In particular, what does for bar in is_Even(k) do in the list comprehension? https://code.sololearn.com/ct6LM6vHhg6G/?ref=app

27th Sep 2020, 12:32 PM
Vitaly Sokol
Vitaly Sokol - avatar
2 Réponses
+ 5
Python implement predicates features . They may succeed or fail. To succeed/fail means that the system was/was'nt able to establish that the predicate holds given the information available. Success or failure is implemented in Python through generators. A generator that yields a result is said to succeed one that does not yield a result, fails. In this case, is_Even(k) succeeds/fails when k is even/odd. (In either case it produces an output line.) When for bar in is_Even(k) succeeds/fails for a given k, the list comprehension completes/fails to complete the iteration for that k and includes/does'nt include k in the generated list.
27th Sep 2020, 12:38 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 2
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-) Then, your code will continue from where it left off each time for uses the generator. Now the hard part: The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting yield. That can be because the loop has come to an end, or because you no longer satisfy an "if/else". This might help... https://stackoverflow.com/questions/7362900/behaviour-of-pythons-yield https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do
27th Sep 2020, 2:34 PM
minirkk
minirkk - avatar