How does this python yield function work?
<pre class="lang-py prettyprint-override"><code>def func():
    output = 0
    while True:
        new = yield output
        output = new


genr = func()
print(next(genr))
print(next(genr))
print(next(genr))
</code></pre>

<p>output:</p>

<blockquote>
  <p>0<br>
  None<br>
  None  </p>
</blockquote>

<p>What i thought is:</p>

<ol>
<li><code>genr=func()</code> return a generator, but does not actually run it.</li>
<li>First <code>print(next(genr))</code> run from the begining of func to <code>yield output</code>, but not yet assign back to <code>new</code>,so output <code>0</code> make sense.  </li>
<li>Second <code>print(next(genr))</code> start from assigning <code>output</code> back to <code>new</code>ï¼and next line <code>output = new</code> make both <code>output</code> and <code>new</code> to 0, next execute <code>yield output</code> should return 0, but why it return <code>None</code> actually?</li>
</ol>

<p>The result of a <a href="https://docs.python.org/3/reference/expressions.html#yieldexpr" rel="nofollow">yield expression</a> is the value sent in by the <a href="https://docs.python.org/3/reference/expressions.html#generator.send" rel="nofollow">generator.send()</a> function, and <code>next(gen)</code> is equivalent to <code>gen.send(None)</code>. So <code>new</code> receives the value <code>None</code> each time you call <code>next()</code>. </p>

<p>If you do this instead:</p>

<pre><code>gen = func()
print(next(gen))     # gets the first value of 'output'
print(next(gen))     # send in None, get None back
print(gen.send(10))  # send in 10, get 10 back
print(gen.send(20))  # send in 20, get 20 back
</code></pre>

<p>you'll get this output:</p>

<pre><code>0
None
10
20
</code></pre>

python yield