Oct-21-2023, 11:05 AM
hi
the below code is in site:https://realpython.com/introduction-to-p...-statement
code:
I have saw before usage of yield like
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:
the below code is in site:https://realpython.com/introduction-to-p...-statement
code:
# from: https://realpython.com/introduction-to-python-generators/ \ #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))On the above page is written:
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
yeild numbut in the above code there is
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:
pal_gen.send(10 ** (digits))thanks.