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!