title: Python scoping rules in nested for loops
body: <p>This is a code to determine if the numbers in the list are prime or not (python2):</p>
  
  <p>this works (1):</p>
  
  <pre><code>    L = [4 , 9, 13, 15, 16]
  
      def primenumber4():
          for i in L:
              compositenumber = False
              for x in range(2,i):
                  if i%x == 0:
                      compositenumber = True              
                      break
              if compositenumber:
                  print "%s is not a prime number" % i        
              else:   
                  print "%s IS a prime number" % i
  
      primenumber4()
  </code></pre>
  
  <p>But this does not (2):</p>
  
  <pre><code>    L = [4 , 9, 13, 15, 16]
  
      def primenumber4():
          compositenumber = False
          for i in L:
              for x in range(2,i):
                 if i%x == 0:
                     compositenumber = True               
                     break
              if compositenumber:
                  print "%s is not a prime number" % i        
              else:   
                  print "%s IS a prime number" % i
  
      primenumber4()
  </code></pre>
  
  <p>it gives the number 13 as not a prime.</p>
  
  <p>But why?</p>
  
  <p>according to this tread:
  <a href="https://stackoverflow.com/questions/291978/short-description-of-scoping-rules/23471004#23471004">Short Description of the Scoping Rules?</a></p>
  
  <p>"One of the greater surprises to many newcomers to Python is that a for loop does not create a variable scope" in Antti Haapala's answer</p>
  
  <p>so I imagine the value "leaks" into the function scope:
  which is the case with a single for loop
  example:</p>
  
  <pre><code>    def function():
          i = 9
          k = False
          for x in range(2, 9):
              if i%x == 0:
                  k = True                
                  break
  
          print k
  </code></pre>
  
  <p>which prints k = True so the variable changed</p>
  
  <p>So my question is: Why doesn't the variable "compositenumber" change in (2)?
  If a for loop doesn't have scope why isn't the variable a local variable in the function? why doesn't it "leak through twice passing both for loops" and ending up as a local variable in the function def.</p>
  
  <p>I'm trying to understand the python scope rules because I don't think I get it completely. Thanks in advance!</p>