473,657 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

isPrime works but UnBoundLocalErr or 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#4 5>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment

>>map(isPrime , range(100))
Traceback (most recent call last):
File "<pyshell#3 8>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocalErr or: 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 1715

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#4 5>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment

>>>map(isPrim e, range(100))

Traceback (most recent call last):
File "<pyshell#3 8>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocalErr or: 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#4 5>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocalEr ror: local variable 'x' referenced before assignment

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

Traceback (most recent call last):
File "<pyshell#3 8>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocalEr ror: local variable 'x' referenced before assignment
>>>>isPrime(1 0)
False
>>>>isPrime(1 1)
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...@y ahoo.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#4 5>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment
>map(isPrime, range(100))

Traceback (most recent call last):
* File "<pyshell#3 8>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment>>isP rime(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...@y ahoo.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#4 5>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment
>>map(isPrime , range(100))
Traceback (most recent call last):
* File "<pyshell#3 8>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment>>isP rime(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...@u bisoft.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#4 5>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment
>>>map(isPrim e, range(100))
Traceback (most recent call last):
* File "<pyshell#3 8>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: 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...@y ahoo.sewrote:
On Jul 15, 7:28*pm, Mensanator <mensana...@aol .comwrote:


On Jul 15, 11:26*am, defn noob <circularf...@y ahoo.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#4 5>", line 1, in <module>
* * [isPrime(y) for y in range(11)]
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment
>map(isPrime, range(100))
Traceback (most recent call last):
* File "<pyshell#3 8>", line 1, in <module>
* * map(isPrime, range(100))
* File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
* * if x == nbr:
UnboundLocalErr or: local variable 'x' referenced before assignment>>>is Prime(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...@y ahoo.sewrote:
>On Jul 15, 7:28 pm, Mensanator <mensana...@aol .comwrote:


>>On Jul 15, 11:26 am, defn noob <circularf...@y ahoo.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#4 5>", line 1, in <module>
[isPrime(y) for y in range(11)]
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocal Error: local variable 'x' referenced before assignment
>>map(isPri me, range(100))
Traceback (most recent call last):
File "<pyshell#3 8>", line 1, in <module>
map(isPrime, range(100))
File "C:\Python25\Pr ogs\blandat\myM ath.py", line 9, in isPrime
if x == nbr:
UnboundLocal Error: local variable 'x' referenced before assignment>>isP rime(10)
False
>>isPrime(1 1)
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
2591
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 happens with 2.2) An import within a function that shadows a global import can raise UnboundLocalError. I think the real problem is that the the local 'import sys' is seen as occuring after the use of sys within this function, even though sys is...
6
9216
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 UnboundLocalError, and after reading the Naming and binding section in the Python docs, I don't see why. Here's the error: >>> fieldprint(, 'rl', ) Traceback (most recent call last): File "<stdin>", line 1, in ?
8
1604
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: item,value=i.split(':') except NameError, UnboundLocalError:
15
2317
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 a list in similar circumstances. The documentation: http://docs.python.org/ref/naming.html does not give me enough info to determine why the difference exists as it does not seem to mention types at all..
9
2421
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
1331
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 list for the Python programming language <python-list.python.org> List-Unsubscribe: <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe> List-Archive:...
2
2052
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... First of all, i don not use any classes in this module. The problem is, that i declare and instantiate some vars outside the functions (global ones), but when i use them inside the functions, i get an "UnboundLocalError" error.
0
839
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
163
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 declarations from "for" loops, and others didn't... I'd say it all follows from the fact that Python doesn't have variable
0
8402
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8315
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8734
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8508
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7341
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6172
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5633
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4164
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2733
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.