title: generator versus nested for loop
body: <p>I have two methods to sum numbers found in a text file.  The first one works and the second one does not.  Can anyone explain what is wrong with the second one?.</p>
  
  <p>Input text file:</p>
  
  <pre><code>The quick brown 123
  fox 456 jumped over
  the 789 lazy dog.
  </code></pre>
  
  <p>Method #1:</p>
  
  <pre><code>total = 0
  for line in open(fn):
      numbers = (int(block) for block in line.split() if block.isdigit())
      total += sum(numbers)
  print('total: ', total)
  </code></pre>
  
  <p>This gives the correct answer 1368 (= 123 + 456 + 789).</p>
  
  <p>Method #2:</p>
  
  <pre><code>numbers = (int(block) for block in line.split() for line in open(fn) if block.isdigit())
  total = sum(numbers)
  print('total: ', total)
  </code></pre>
  
  <p>This produces the error:</p>
  
  <pre><code>NameError: name 'line' is not defined
  </code></pre>
  
  <p>I'm playing around with generators so the question is really about why the generator in method #2 is no good.  I don't need suggestions on <em>other</em> ways to add up numbers in a text file.  I would like to know if there is a generator-only solution without a standard for loop.  Thank you.</p>