Reputation: 7
I'm an amateur programmer and would like to seek advice while learning codes. Here I encounter some issues.
I found that when I remove the comment "#X=3" and make it into a code from the below then the code works. Without X=3, the code results into UnboundLocalError.
Browsed online, it's related to global and local variable but I can't see how it's related. And when does X has to be denoted before the while loop? and why "for y in primes" doesn't need to pre-define "y"?
Main purpose of the code: count the # of prime numbers up to (num)
def count_primes2(num):
primes = [2]
#x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
Upvotes: 0
Views: 68
Reputation: 59466
You need to create (and assign a value to) a variable before you use it. If you try to use a variable's value before creating the variable, then you get the exception. You do exactly this in the while
expression: You ask if its value is below or equal to num
, but it does not even exist yet, it has no value, this raises the exception.
Now, why do you get the UnboundLocalError
?
The compiler goes through your code before the code gets executed. In this compile step it notices that you somewhere in your function assign a value to X
, namely in the line x += 2
. (There are even two of them.) This marks the variable for the compiler as a local variable.
So if you try to access the variable before the assignment takes place, the variable doesn't exist yet, but the code already knows that is supposed to be a local variable, hence the UnboundLocalError
.
Without any assignment statement to X
in the function you would have gotten a NameError
because during execution of the while
statement the interpreter then searches for a global variable of this name.
Upvotes: 1
Reputation: 3054
To expand, since you are using x in the while loop criteria, yes, it has to be defined before. You don't need to define y
before the for loop because the for y in primes
line defines y
as each item in the list.
A rough translation to plain English:
while x <= num:
== As long as this number is less than or equal to this other number, do the following
for y in primes
== do the following for each item, named y, in primes
hopefully that wasn't more confusing
Upvotes: 1
Reputation: 217
As per design pattern variable should be created just before to use. In the code you are using x without creating or initializing default value. "y" = you are iterating the list (primes). So in each iteration y will be initialized by the current value.So it will not give any error.
Upvotes: 2