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

Home Posts Topics Members FAQ

UnboundLocalErr or

hi all

why it generates an "UnboundLocalEr ror" when I do the following:

<code>
....
def main():
number = number()
number_user = user_guess()
while number_user != number:
check_number(nu mber = number, number_user = number_user)
number_user = user_guess()

UnboundLocalErr or: local variable 'number' referenced before assignment
</code>

I found when I changed the number() to num() or whatever the issue
solved
but doesn't every function has its own namespace?
Can anyone please explain it to me?

Peace

Nov 9 '06 #1
9 2421
Hello,

Camellia wrote:
why it generates an "UnboundLocalEr ror" when I do the following:

<code>
...
def main():
number = number()
number_user = user_guess()
while number_user != number:
check_number(nu mber = number, number_user = number_user)
number_user = user_guess()

UnboundLocalErr or: local variable 'number' referenced before assignment
</code>

I found when I changed the number() to num() or whatever the issue
solved
but doesn't every function has its own namespace?
Can anyone please explain it to me?
When Python compiles your code, it sees that you are using a local
variable 'number' in this function ('number = ...') and probably allocates
some memory for it or whatever - ask the core Python hackers for details.
When this statement is executed, the right hand side is evaluated first and
Python finds a reference to 'number'. It knows that number is a local
variable in main(), but has not been assigned yet (which would happend
after the right hand side is evaluated) - thus the error.

Even if you could get this to work, you have two 'number's in the function
with different meaning, which just makes understanding the code too
difficult.

Is number() (the global one) a function or class. I guess it's a function,
so I would suggest to name it 'get_number' (and same
for 'get_user_guess ') - this makes the code more descriptive. Should it
really be a class, a common convention is to capitalize it 'Number()'.
HTH

--
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
Nov 9 '06 #2

"Camellia" <br*********@gm ail.comwrote in message
news:11******** **************@ i42g2000cwa.goo glegroups.com.. .
hi all

why it generates an "UnboundLocalEr ror" when I do the following:

<code>
...
Presumably, the elided code includes a 'def number():' statement
def main():
number = number()
Within a function, a given name can be either global or local, but not
both.
Here you are expecting the compiler to interpret the first occurance of
'number' as local and the second as global. Humans can often resolve such
ambiguities correctly, but not necessarily always. So this is too much to
ask of a program and hence it is not allowed.

As Benjamin said, use two different names for the two different objects
that you need to use in the same context.

Terry Jan Reedy


Nov 9 '06 #3
Terry Reedy wrote in
news:ma******** *************** *************** *@python.org in
comp.lang.pytho n:
>def main():
number = number()

Within a function, a given name can be either global or local, but not
both.
Here you are expecting the compiler to interpret the first occurance
of 'number' as local and the second as global. Humans can often
resolve such ambiguities correctly, but not necessarily always. So
this is too much to ask of a program and hence it is not allowed.
".. asked too much of the programme", sounds like a BOFH excuse to
me ;-).

Seriously I'd bet (if I were a gambling man) that this is by design,
not either of "too much work for the interpreter" or "nobody's
submitted a patch".

IOW: Why should the intepreter do more work just so the user
can find new and interesting ways to shoot them selves in the foot.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Nov 9 '06 #4
Thank you all so much for all the replies:)

But sorry I'm so dumb I can't say I really understand,
what do I actually do when I define a function with its name "number"?
why does a name of a function has something to do with a variable?

Oh wait can I do this in Python?:
<code>
def a():
def b()
</code>

so the b() will appear to be a local function which is the possible
cause of my little own error because the compiler will interpret the
number() as a local function but a global one?

On Nov 10, 7:32 am, Rob Williscroft <r...@freenet.c o.ukwrote:
Terry Reedy wrote innews:ma****** *************** *************** ***@python.orgi n
comp.lang.pytho n:
def main():
number = number()
Within a function, a given name can be either global or local, but not
both.
Here you are expecting the compiler to interpret the first occurance
of 'number' as local and the second as global. Humans can often
resolve such ambiguities correctly, but not necessarily always. So
this is too much to ask of a program and hence it is not allowed.".. asked too much of the programme", sounds like a BOFH excuse to
me ;-).

Seriously I'd bet (if I were a gambling man) that this is by design,
not either of "too much work for the interpreter" or "nobody's
submitted a patch".

IOW: Why should the intepreter do more work just so the user
can find new and interesting ways to shoot them selves in the foot.

Rob.
--http://www.victim-prime.dsl.pipex .com/
Nov 11 '06 #5
At Saturday 11/11/2006 02:35, Camellia wrote:
>But sorry I'm so dumb I can't say I really understand,
what do I actually do when I define a function with its name "number"?
Don't apologize, Python is a lot more dumb than you. It obeys very
simple rules (a good thing, so we can clearly understand them, once
we know them).
Recalling your previous example:
>def main():
> number = number()
Python first scans the source code looking for assigned-to names.
That is, names to the left of equal signs. Those names, plus the
function formal parameters, make the list of "local names". Any other
names referenced are assumed to be globals, that is, living outside
your function. (That's not entirely true but enough for now).
Notice that "number" is a local name because it's assigned to; it
doesn't matter whether a global name "number" exists or not.
When the code is executed, the "number" to the right references the
local name, which has not been assigned to yet - that's why you get
an UnboundLocalErr or. "number" can't be a global name when used on
the right hand side, and a local name when used on the left hand
side. It's simple: it is local, or not, but not both.
>why does a name of a function has something to do with a variable?
Notice also that it does not matter *what* kind of object a name
refers to: it may be a function, a class, an object instance,
whatever. Inside a function, by example, a local name "a" may be
bound at most to a single object at a time, it doesn't matter its
type. A local name "a" can't refer to an integer and a class at the same time.
The left hand side of an assign statement *always* uses local names,
except when you declare a name to be global by using the "global" keyword.
And notice also that I've never used the word variable.
>Oh wait can I do this in Python?:
<code>
def a():
def b()
</code>

so the b() will appear to be a local function which is the possible
cause of my little own error because the compiler will interpret the
number() as a local function but a global one?
Yes, you can. Python has "lexically nested scopes". The simple
local/global rule of above is a bit more complicated: when a name is
not local, it is searched inside the enclosing functions, then in the
containing module's global namespace, and last in the builtin names.
And yes, b is local to a, so it effectively hides any external b that
could be in outer scopes.
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 11 '06 #6
Oh how can I thank you enough, you make my day:)
According to what you said I finally figure it out, it is the same as:

<code>
b = 1
def a():
b = b #no good:)
</code>

So in every day programming I should avoid using the same name for
different objects because they will step on each other, right?

On Nov 11, 6:18 pm, Gabriel Genellina <gagsl...@yahoo .com.arwrote:
At Saturday 11/11/2006 02:35, Camellia wrote:
But sorry I'm so dumb I can't say I really understand,
what do I actually do when I define a function with its name "number"?Do n't apologize, Python is a lot more dumb than you. It obeys very
simple rules (a good thing, so we can clearly understand them, once
we know them).
Recalling your previous example:
def main():
number = number()Python first scans the source code looking for assigned-to names.
That is, names to the left of equal signs. Those names, plus the
function formal parameters, make the list of "local names". Any other
names referenced are assumed to be globals, that is, living outside
your function. (That's not entirely true but enough for now).
Notice that "number" is a local name because it's assigned to; it
doesn't matter whether a global name "number" exists or not.
When the code is executed, the "number" to the right references the
local name, which has not been assigned to yet - that's why you get
an UnboundLocalErr or. "number" can't be a global name when used on
the right hand side, and a local name when used on the left hand
side. It's simple: it is local, or not, but not both.
why does a name of a function has something to do with a variable?Notice also that it does not matter *what* kind of object a name
refers to: it may be a function, a class, an object instance,
whatever. Inside a function, by example, a local name "a" may be
bound at most to a single object at a time, it doesn't matter its
type. A local name "a" can't refer to an integer and a class at the same time.
The left hand side of an assign statement *always* uses local names,
except when you declare a name to be global by using the "global" keyword.
And notice also that I've never used the word variable.
Oh wait can I do this in Python?:
<code>
def a():
def b()
</code>
so the b() will appear to be a local function which is the possible
cause of my little own error because the compiler will interpret the
number() as a local function but a global one?Yes, you can. Python has "lexically nested scopes". The simple
local/global rule of above is a bit more complicated: when a name is
not local, it is searched inside the enclosing functions, then in the
containing module's global namespace, and last in the builtin names.
And yes, b is local to a, so it effectively hides any external b that
could be in outer scopes.

--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! -http://correo.yahoo.co m.ar
Nov 11 '06 #7
Oh how can I thank you enough, you make my day:)
According to what you said I finally figure it out, it is the same as:

<code>
b = 1
def a():
b = b #no good:)
</code>

So in every day programming I should avoid using the same name for
different types of objects because they will step on each other, right?

On Nov 11, 6:18 pm, Gabriel Genellina <gagsl...@yahoo .com.arwrote:

On Nov 11, 6:18 pm, Gabriel Genellina <gagsl...@yahoo .com.arwrote:
At Saturday 11/11/2006 02:35, Camellia wrote:
But sorry I'm so dumb I can't say I really understand,
what do I actually do when I define a function with its name "number"?Do n't apologize, Python is a lot more dumb than you. It obeys very
simple rules (a good thing, so we can clearly understand them, once
we know them).
Recalling your previous example:
def main():
number = number()Python first scans the source code looking for assigned-to names.
That is, names to the left of equal signs. Those names, plus the
function formal parameters, make the list of "local names". Any other
names referenced are assumed to be globals, that is, living outside
your function. (That's not entirely true but enough for now).
Notice that "number" is a local name because it's assigned to; it
doesn't matter whether a global name "number" exists or not.
When the code is executed, the "number" to the right references the
local name, which has not been assigned to yet - that's why you get
an UnboundLocalErr or. "number" can't be a global name when used on
the right hand side, and a local name when used on the left hand
side. It's simple: it is local, or not, but not both.
why does a name of a function has something to do with a variable?Notice also that it does not matter *what* kind of object a name
refers to: it may be a function, a class, an object instance,
whatever. Inside a function, by example, a local name "a" may be
bound at most to a single object at a time, it doesn't matter its
type. A local name "a" can't refer to an integer and a class at the same time.
The left hand side of an assign statement *always* uses local names,
except when you declare a name to be global by using the "global" keyword.
And notice also that I've never used the word variable.
Oh wait can I do this in Python?:
<code>
def a():
def b()
</code>
so the b() will appear to be a local function which is the possible
cause of my little own error because the compiler will interpret the
number() as a local function but a global one?Yes, you can. Python has "lexically nested scopes". The simple
local/global rule of above is a bit more complicated: when a name is
not local, it is searched inside the enclosing functions, then in the
containing module's global namespace, and last in the builtin names.
And yes, b is local to a, so it effectively hides any external b that
could be in outer scopes.

--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! -http://correo.yahoo.co m.ar
Nov 11 '06 #8
Camellia wrote:
Oh how can I thank you enough, you make my day:)
According to what you said I finally figure it out, it is the same as:

<code>
b = 1
def a():
b = b #no good:)
</code>
if you really want to modify a variable that lives outside the function,
you can use the "global" directive:

http://effbot.org/pyfaq/how-do-you-s...a-function.htm
So in every day programming I should avoid using the same name for
different types of objects because they will step on each other,
right?
if you want to distinguish between things, giving them distinct names is
always a good idea.

</F>

Nov 11 '06 #9
Oh thank you for pointing that out Fredrik, you made the case more
clear:)

On Nov 11, 7:19 pm, Fredrik Lundh <fred...@python ware.comwrote:
Camellia wrote:
Oh how can I thank you enough, you make my day:)
According to what you said I finally figure it out, it is the same as:
<code>
b = 1
def a():
b = b #no good:)
</code>if you really want to modify a variable that lives outside the function,
you can use the "global" directive:

http://effbot.org/pyfaq/how-do-you-s...e-in-a-functio...
So in every day programming I should avoid using the same name for
different types of objects because they will step on each other,
right?

if you want to distinguish between things, giving them distinct names is
always a good idea.

</F>
Nov 11 '06 #10

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 ?
2
5022
by: silverburgh.meryl | last post by:
Can you please tell me what is the meaning this error in general? UnboundLocalError: local variable 'colorIndex' referenced before assignment In my python script, I have a variable define and init to 0, like this colorIndex = 0 and in one of my functions, I increment it by 1
8
1605
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..
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.
8
1716
by: defn noob | last post by:
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
0
8425
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
8743
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
8522
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
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7355
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
6177
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
5647
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
4173
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...
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.