473,320 Members | 2,104 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

scope of variables

Hi

is the code below correct?

b = 3
def adding(a)
print a + b

it seams not to see the up-level scope where b is defined.

thanks
May 3 '06 #1
11 1181
In <87************@localhost.localdomain>, Gary Wessle wrote:
is the code below correct?
No...
b = 3
def adding(a)
....a colon is missing at the end of the above line.
print a + b

it seams not to see the up-level scope where b is defined.


It does. And you could easily find out yourself by just trying that code.
Running this::

b = 3
def adding(a):
print a + b

adding(5)

Puts out 8 as expected.

Ciao,
Marc 'BlackJack' Rintsch
May 3 '06 #2
On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote:
b = 3
def adding(a)
print a + b

it seams not to see the up-level scope where b is defined.


Assuming you put a ':' after the "def adding(a)", this should work in
recent versions of Python. In Python 2.0 and older, this will not work.
In Python 2.1, it will only work if you do this:

from __future__ import nested_scopes
When you first start Python interactively, it should print version
information. Here's what my Python prints when I start it:

Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
As you can see, I'm running Python 2.4.3. Make sure you aren't running an
old version of Python, and that code should do what you expect.
--
Steve R. Hastings "Vita est"
st***@hastings.org http://www.blarg.net/~steveha

May 3 '06 #3
Gary Wessle <ph****@yahoo.com> writes:
is the code below correct?
It's best to post an example that you've tried yourself, and that is
small but completely demonstrates the issue in question.
b = 3
def adding(a)
print a + b


This, for example, would fail the syntax check (the 'def' statement
needs a trailing colon). After that's fixed, the code runs, but shows
no output.

A complete, minimal, working example will help people answer your
question.

--
\ "[W]e are still the first generation of users, and for all that |
`\ we may have invented the net, we still don't really get it." |
_o__) -- Douglas Adams |
Ben Finney

May 3 '06 #4
"Steve R. Hastings" <st***@hastings.org> writes:
On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote:
b = 3
def adding(a)
print a + b

it seams not to see the up-level scope where b is defined.


Assuming you put a ':' after the "def adding(a)", this should work in
recent versions of Python. In Python 2.0 and older, this will not work.


the example was an in-accuretlly representation of a the problem I am
having. my apologies.

a = []
def prnt():
print len(a)
prnt

<function prnt at 0xb7dc21b4>

I expect to get 0 "the length of list a"
May 3 '06 #5
Gary Wessle wrote:
the example was an in-accuretlly representation of a the problem I am
having. my apologies.

a = []
def prnt():
print len(a)
prnt <function prnt at 0xb7dc21b4>

I expect to get 0 "the length of list a"


Python requires parenthesis to call a function.
a = []
def prnt(): ... print len(a)
... prnt <function prnt at 0xb7dcad84> prnt()

0
May 3 '06 #6
Try >>> prnt()
o.o'

On 04 May 2006 08:25:01 +1000, Gary Wessle <ph****@yahoo.com> wrote:
"Steve R. Hastings" <st***@hastings.org> writes:
On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote:
b = 3
def adding(a)
print a + b

it seams not to see the up-level scope where b is defined.


Assuming you put a ':' after the "def adding(a)", this should work in
recent versions of Python. In Python 2.0 and older, this will not work..


the example was an in-accuretlly representation of a the problem I am
having. my apologies.

a = []
def prnt():
print len(a)
prnt

<function prnt at 0xb7dc21b4>

I expect to get 0 "the length of list a"
--
http://mail.python.org/mailman/listinfo/python-list

--
Lord Landon rules over all!
May 3 '06 #7
Gary Wessle wrote:
the example was an in-accuretlly representation of a the problem I am
having. my apologies.

a = []
def prnt():
print len(a)
prnt <function prnt at 0xb7dc21b4>

I expect to get 0 "the length of list a"


You want prnt(), not prnt:
a = []
def prnt(): .... print len(a)
.... prnt <function prnt at 0x43c70> prnt()

0

--Ryan
May 3 '06 #8
> is the code below correct?

b = 3
def adding(a)
print a + b

it seams not to see the up-level scope where b is defined.


Yes except for the missing : at the end of the "def" line.

Rob

May 4 '06 #9
Ryan Forsythe <ry**@cs.uoregon.edu> writes:
Gary Wessle wrote:
the example was an in-accuretlly representation of a the problem I am
having. my apologies.

a = []
def prnt():
print len(a)
> prnt

<function prnt at 0xb7dc21b4>

I expect to get 0 "the length of list a"


You want prnt(), not prnt:


I finally was able to duplicate the error with a through away code
as follows,

************************************************** **************
acc = [1,2,3]

def a():
b = [4, 5, 6]
acc = acc + b
print len(acc)

a()

**************** error ****************
Traceback (most recent call last):
File "a.py", line 12, in ?
a()
File "a.py", line 9, in a
acc = acc + b
UnboundLocalError: local variable 'acc' referenced before assignment
May 4 '06 #10
Gary Wessle wrote:
Ryan Forsythe <ry**@cs.uoregon.edu> writes:

Gary Wessle wrote:
the example was an in-accuretlly representation of a the problem I am
having. my apologies.
(snip) I finally was able to duplicate the error with a through away code
as follows,

************************************************** **************
acc = [1,2,3]

def a():
b = [4, 5, 6]
acc = acc + b
print len(acc)

a()

**************** error ****************
Traceback (most recent call last):
File "a.py", line 12, in ?
a()
File "a.py", line 9, in a
acc = acc + b
UnboundLocalError: local variable 'acc' referenced before assignment


This is a FAQ:
http://www.python.org/doc/faq/progra...bles-in-python

For short: if a name is 'assigned' (in Python, the correct term is
'bound') in the local scope, it'll be considered a local name. If it's
*only* accessed, it'll be looked up in the enclosing namespace - here
the so-called 'global' (which means: 'module') namespace.

The dirty solution is to declare 'acc' as global in the function:
def a():
b = [4, 5, 6]
global acc
acc = acc + b
print len(acc)

but this is really BadCode(tm). As a general rule, functions should not
silently modify or rebind global variables - this leads to maintenance
nightmares. In this case, you should manage to either 1/ pass acc as a
param to a(), or 2/ have a() return the sequence to be added to acc:

# 1
acc = [1,2,3]
def a(alist):
alist.extend([4, 5, 6])
return alist

acc = a(acc)
print acc, len(acc)

# 2
acc = [1,2,3]
def a():
return [4, 5, 6]

acc.extend(a())
print acc, len(acc)
The Right Thing(tm) to do of course depends on the real code, so it may
be yet another solution, but it's impossible to decide with dummy code...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 4 '06 #11
thank you
May 4 '06 #12

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

Similar topics

6
by: Hal Vaughan | last post by:
Being self taught, this is one thing I've always had trouble with -- I finally get it straight in one situation and I find I'm not sure about another. I have a class that keeps calling an...
33
by: Arthur | last post by:
>>>a= >>> for p in a: print p 1 2 3 >>> p 3 My naive expectation was that p would be 'not defined' from outside
3
by: Anonymous | last post by:
Is namespace the same thing as scope? While reading the book "Thinking in C++", I was under the impression that namespace is, well, a namespace--a feature to create a hiearchy for identifiers...
6
by: pembed2003 | last post by:
Hi all, I am reading the book "C++ How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope...
3
by: Grant Wagner | last post by:
Given the following working code: function attributes() { var attr1 = arguments || '_'; var attr2 = arguments || '_'; return ( function (el1, el2) { var value1 = el1 + el1; var value2 = el2...
5
by: pembed2003 | last post by:
Hi all, I am reading the book "C How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope...
7
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9...
1
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause...
0
MMcCarthy
by: MMcCarthy | last post by:
We often get questions on this site that refer to the scope of variables and where and how they are declared. This tutorial is intended to cover the basics of variable scope in VBA for MS Access. For...
5
by: chromis | last post by:
Hi there, I've recently been updating a site to use locking on application level variables, and I am trying to use a commonly used method which copies the application struct into the request...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.