hi
the below code is in site:https://realpython.com/introduction-to-p...-statement
code:
On the above page is written:
I have saw before usage of yield like
but in the above code there is
.
which of them are statements and which are expressions. also, plz, explain the above text that has been written on the mentioned page.
why the line if i is not None: is used?
explain about:
thanks.
the below code is in site:https://realpython.com/introduction-to-p...-statement
code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#understanding-the-python-yield-statement def is_palindrome(num): # Skip single-digit inputs if num / / 10 = = 0 : return False temp = num reversed_num = 0 while temp ! = 0 : reversed_num = (reversed_num * 10 ) + (temp % 10 ) temp = temp / / 10 if num = = reversed_num: return True else : return False def infinite_palindromes(): num = 0 while True : if is_palindrome(num): print (num) i = ( yield num) if i is not None : num = i num + = 1 if __name__ = = "__main__" : pal_gen = infinite_palindromes() for i in pal_gen: digits = len ( str (i)) if digits = = 5 : pal_gen.throw(ValueError( "We don't like large palindromes" )) pal_gen.send( 10 * * (digits)) |
Quote:As of Python 2.5 (the same release that introduced the methods you are learning about now), yield is an expression, rather than a statement. Of course, you can still use it as a statement. But now, you can also use it as you see in the code block above, where i takes the value that is yielded. This allows you to manipulate the yielded value. More importantly, it allows you to .send() a value back to the generator. When execution picks up after yield, i will take the value that is sent..I before wrote a threat about statement and expression and asked about them:https://python-forum.io/thread-40934.html
I have saw before usage of yield like
1 |
yeild num |
1 |
i = ( yield num) |
which of them are statements and which are expressions. also, plz, explain the above text that has been written on the mentioned page.
why the line if i is not None: is used?
explain about:
1 |
pal_gen.send( 10 * * (digits)) |