1

This is a code to determine if the numbers in the list are prime or not (python2):

this works (1):

    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()

But this does not (2):

    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()

it gives the number 13 as not a prime.

But why?

according to this tread: Short Description of the Scoping Rules?

"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

so I imagine the value "leaks" into the function scope: which is the case with a single for loop example:

    def function():
        i = 9
        k = False
        for x in range(2, 9):
            if i%x == 0:
                k = True                
                break

        print k

which prints k = True so the variable changed

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.

I'm trying to understand the python scope rules because I don't think I get it completely. Thanks in advance!

Community
  • 1
  • 1
stef
  • 23
  • 1
  • 5

1 Answers1

1

This is not a scope issue. The issue is that when you assign primenumber = False inside the for loop, that assignment happens every time you go through the loop. It resets the value to False every time.

When you assign primenumber = False above the loop, it only gets assigned that way once, so primenumber remains True after the first time it's set to True.

Also, primenumber is a terrible name for a variable that indicates whether a number is composite.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Haha I quickly edited that. I was a bit confused when writing this up it seems. And thanks! easy answer. I feel stupid for not seeing that myself – stef Mar 08 '17 at 22:35