472,364 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,364 software developers and data experts.

isPrime works but UnBoundLocalError when mapping on list

isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False
>>[isPrime(y) for y in range(11)]
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment

>>map(isPrime, range(100))
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>>isPrime(10)
False
>>isPrime(11)
True

adding x=1 makes it work though:

def isPrime(nbr):
x=1
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

>>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
Jul 15 '08 #1
8 1618

defn noob wrote:
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False
>>>[isPrime(y) for y in range(11)]

Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment

>>>map(isPrime, range(100))

Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>>>isPrime(10)
False
>>>isPrime(11)
True

adding x=1 makes it work though:

def isPrime(nbr):
x=1
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

>>>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
--
http://mail.python.org/mailman/listinfo/python-list
========================================
Yep - "local variable 'x' referenced before assignment" is correct.
You state: for x in range... but x doesn't exist until initialized.
To save a loop, initialize x=2 (the minimum value) and loop executes
on pass one.
In a straight 'C' program
( for (x=1, x=(nbr+1), x++) etc... )
the x is initialized and forceably incremented.
seems Python does not auto initialize but does auto increment.
Steve
no******@hughes.net
Jul 15 '08 #2
>defn noob wrote:
>isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False
>>>>[isPrime(y) for y in range(11)]

Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment

>>>>map(isPrime, range(100))

Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>>>>isPrime(10)
False
>>>>isPrime(11)
True

adding x=1 makes it work though:

def isPrime(nbr):
x=1
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

>>>>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
--
http://mail.python.org/mailman/listinfo/python-list

========================================
Yep - "local variable 'x' referenced before assignment" is correct.
You state: for x in range... but x doesn't exist until initialized.
To save a loop, initialize x=2 (the minimum value) and loop executes
on pass one.
In a straight 'C' program
( for (x=1, x=(nbr+1), x++) etc... )
the x is initialized and forceably incremented.
seems Python does not auto initialize but does auto increment.
I think a better explanation is that in your original function, x only
existed while the for loop was running. As soon as execution hit the
break statement, x ceased to exist. When you attempted to reference it
in the next line, Python has no variable called x so it complains that x
hasn't been initialised.

A more idiomatic way to write it...

def isPrime(nbr):
if nbr <= 1:
return False
for x in xrange(2, nbr+1):
if not nbr % x:
return x == nbr

Cheers,

Drea
Jul 15 '08 #3
On Jul 15, 11:26*am, defn noob <circularf...@yahoo.sewrote:
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?

def isPrime(nbr):
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>[isPrime(y) for y in range(11)]

Traceback (most recent call last):
* File "<pyshell#45>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>map(isPrime, range(100))

Traceback (most recent call last):
* File "<pyshell#38>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment>>isPrime(10)
False
>isPrime(11)

True

adding x=1 makes it work though:

def isPrime(nbr):
* * x=1
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>[isPrime(y) for y in range(11)]

[False, True, True, True, False, True, False, True, False, False,
False]
No, it doesn't. You are falsely reporting that 1 is prime.

And instead of making the fake variable x, shouldn't you
instead test that nbr+1 is greater than 2? Or call it with
range(3,11) instead of range(11)? x isn't initialized
because if nbr+1 is <=2, the for loop has an invalid range
and doesn't even execute.
Jul 15 '08 #4
On Jul 15, 7:28*pm, Mensanator <mensana...@aol.comwrote:
On Jul 15, 11:26*am, defn noob <circularf...@yahoo.sewrote:
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>>[isPrime(y) for y in range(11)]
Traceback (most recent call last):
* File "<pyshell#45>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>>map(isPrime, range(100))
Traceback (most recent call last):
* File "<pyshell#38>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment>>isPrime(10)
False
>>isPrime(11)
True
adding x=1 makes it work though:
def isPrime(nbr):
* * x=1
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]

No, it doesn't. You are falsely reporting that 1 is prime.

And instead of making the fake variable x, shouldn't you
instead test that nbr+1 is greater than 2? Or call it with
range(3,11) instead of range(11)? x isn't initialized
because if nbr+1 is <=2, the for loop has an invalid range
and doesn't even execute.

def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

this works for all primes, if i want to not include 1 i just do if
nbr<=1 return false

you are answering the wrong question.
anyway here is a clear one:
def isPrime(nbr):
if nbr < 2:
return False
for x in range(2, nbr + 1):
if nbr % x == 0:
return nbr == x
Jul 15 '08 #5
On Jul 15, 12:28*pm, "Andreas Tawn" <andreas.t...@ubisoft.comwrote:
defn noob wrote:
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>>>[isPrime(y) for y in range(11)]
Traceback (most recent call last):
* File "<pyshell#45>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>>>map(isPrime, range(100))
Traceback (most recent call last):
* File "<pyshell#38>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
isPrime(10)
False
isPrime(11)
True
adding x=1 makes it work though:
def isPrime(nbr):
* * x=1
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>>>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
--
http://mail.python.org/mailman/listinfo/python-list
========================================
Yep - "local variable 'x' referenced before assignment" is correct.
You state: for x in range... but x doesn't exist until initialized.
* To save a loop, initialize x=2 (the minimum value) and loop executes
* on pass one.
In a straight 'C' program
* ( *for (x=1, x=(nbr+1), x++) *etc... *)
* the x is initialized and forceably incremented.
* seems Python does not auto initialize but does auto increment.

I think a better explanation is that in your original function, x only
existed while the for loop was running.
The for loop never ran.
As soon as execution hit the break statement,
It never hit the break statement, the first call from
[isPrime(y) for y in range(11)]
attempted to do for x in range(2,1).
x ceased to exist.
Something has to exist before it can cease to exist.
When you attempted to reference it
in the next line, Python has no variable called x so it complains that x
hasn't been initialised.
Right conlusion but false premise.
>
A more idiomatic way to write it...

def isPrime(nbr):
* * if nbr <= 1:
* * * * return False
* * for x in xrange(2, nbr+1):
* * * * if not nbr % x:
* * * * * * return x == nbr

Cheers,

Drea
Jul 15 '08 #6
On Jul 15, 12:36*pm, defn noob <circularf...@yahoo.sewrote:
On Jul 15, 7:28*pm, Mensanator <mensana...@aol.comwrote:


On Jul 15, 11:26*am, defn noob <circularf...@yahoo.sewrote:
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>[isPrime(y) for y in range(11)]
Traceback (most recent call last):
* File "<pyshell#45>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>map(isPrime, range(100))
Traceback (most recent call last):
* File "<pyshell#38>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment>>>isPrime(10)
False
>isPrime(11)
True
adding x=1 makes it work though:
def isPrime(nbr):
* * x=1
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False
>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
No, it doesn't. You are falsely reporting that 1 is prime.
And instead of making the fake variable x, shouldn't you
instead test that nbr+1 is greater than 2? Or call it with
range(3,11) instead of range(11)? x isn't initialized
because if nbr+1 is <=2, the for loop has an invalid range
and doesn't even execute.

def isPrime(nbr):
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * break
* * if x == nbr:
* * * * return True
* * else:
* * * * return False

this works for all primes, if i want to not include 1 i just do if
nbr<=1 return false

you are answering the wrong question.
No, I also mentioned the for loop having an invalid range,
which is why your original failed.

Pointing out that 1 isn't prime was a bonus.
>
anyway here is a clear one:
def isPrime(nbr):
* * if nbr < 2:
* * * * return False
* * for x in range(2, nbr + 1):
* * * * if nbr % x == 0:
* * * * * * return nbr == x
I suppose you're not interested in knowing you don't
have to test anything higher than the square root of
the number.

Jul 15 '08 #7

Mensanator wrote:
On Jul 15, 12:36 pm, defn noob <circularf...@yahoo.sewrote:
>On Jul 15, 7:28 pm, Mensanator <mensana...@aol.comwrote:


>>On Jul 15, 11:26 am, defn noob <circularf...@yahoo.sewrote:
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?
def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False
>>[isPrime(y) for y in range(11)]
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
>>map(isPrime, range(100))
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment>>isPrime(10)
False
>>isPrime(11)
True
adding x=1 makes it work though:
def isPrime(nbr):
x=1
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False
>>[isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
No, it doesn't. You are falsely reporting that 1 is prime.
And instead of making the fake variable x, shouldn't you
instead test that nbr+1 is greater than 2? Or call it with
range(3,11) instead of range(11)? x isn't initialized
because if nbr+1 is <=2, the for loop has an invalid range
and doesn't even execute.
def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

this works for all primes, if i want to not include 1 i just do if
nbr<=1 return false

you are answering the wrong question.

No, I also mentioned the for loop having an invalid range,
which is why your original failed.

Pointing out that 1 isn't prime was a bonus.
>anyway here is a clear one:
def isPrime(nbr):
if nbr < 2:
return False
for x in range(2, nbr + 1):
if nbr % x == 0:
return nbr == x

I suppose you're not interested in knowing you don't
have to test anything higher than the square root of
the number.

--
http://mail.python.org/mailman/listinfo/python-list
===========================
"don't...test...higher than the square root..."

I wondered when that was going to show up.
I too had a good math teacher.

Steve
no******@hughes.net
Jul 15 '08 #8


Andreas Tawn wrote:
I think a better explanation is that in your original function, x only
existed while the for loop was running. As soon as execution hit the
break statement, x ceased to exist.
Wrong. For loop variables continue after the loop exits. This is
intentional. Mensanator gave the correct explanation (loop never enters
for nbr==1).

Jul 15 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Brad Clements | last post by:
I was going to file this as a bug in the tracker, but maybe it's not really a bug. Poor Python code does what I consider to be unexpected. What's your opinion? With Python 2.3.2 (but also...
6
by: Alex Gittens | last post by:
I'm trying to define a function that prints fields of given widths with specified alignments; to do so, I wrote some helper functions nested inside of the print function itself. I'm getting an...
8
by: David Bear | last post by:
I'm attempting to use the cgi module with code like this: import cgi fo = cgi.FieldStorage() # form field names are in the form if 'name:part' keys = fo.keys() for i in keys: try:...
15
by: Paddy | last post by:
Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing...
9
by: Camellia | last post by:
hi all why it generates an "UnboundLocalError" when I do the following: <code> .... def main(): number = number() number_user = user_guess() while number_user != number:
0
by: henk-jan ebbers | last post by:
Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.9 Precedence: list List-Id: General discussion...
2
by: Konstantinos Pachopoulos | last post by:
Hi, i have a problem, the source of which is probably the fact, that i have not understood how to declare global variables - I use the Jython compiler, but i think this is a Python issue... ...
0
by: Andreas Tawn | last post by:
I don't have experience of too many other languages, but in C++ (and I guess C)... for (int i=0; i<10; ++i) { doStuff(i); } doStuff(i); // Error
0
by: Fredrik Lundh | last post by:
Andreas Tawn wrote: That's invalid C (you cannot declare variables in the "for" statement itself, at least not in C89). And back in the old days, some C++ compilers did in fact leak...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.