By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,097 Members | 1,580 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,097 IT Pros & Developers. It's quick & easy.

Question about "global" statement

ChrisWang
P: 9
Hi,

I am having trouble understanding the use of 'global' variables I want to use a global variable with the same name as a parameter of a function. But I don't know how to use them at the same time. Here is a snippet of example code:

Expand|Select|Wrap|Line Numbers
  1. def foo (a):
  2.     global p
  3.     global a
  4.     p = a + 3  #here "a" will be reference to the global one
  5.  
  6. a = 1
  7. p = 0
  8. foo (a)
  9. print a, p
When I executed this script, Python said "SyntaxError: name 'a' is local and global". I don't think there is anything wrong with Python, but just want to find a way to use local and global variable in one function. In CPP, we can use :: prefix to indicate the variable is global. But I have no idea that how to implement it in Python. Could anybody tell me the solution?

Thanks!
Nov 20 '08 #1
Share this Question
Share on Google+
4 Replies


Smygis
100+
P: 126
If you have to use global variables my favorite way is to crate a container for the global variables, like this:

Expand|Select|Wrap|Line Numbers
  1. >>> class gv: pass
  2. ... 
  3. >>> def foo():
  4. ...     gv.p = gv.a + 3
  5. ... 
  6. >>> gv.p, gv.a = 0, 1
  7. >>> foo()
  8. >>> print gv.a, gv.p
  9. 1 4
  10. >>> 
  11.  
Anyway what you are doing wrong is exactly what the error message says. There is two "a" and python gets confused as to whom of them you are referring to.
Expand|Select|Wrap|Line Numbers
  1. >>> def bar(a):
  2. ...     global a
  3. ...     print a
  4. ... 
  5. SyntaxError: name 'a' is local and global
  6.  
Solve it by using different variable names. This is why i prefer to create the container for global variables. Its to keep them separate form the other variables.
Nov 20 '08 #2

ChrisWang
P: 9
Good suggestion! Thanks!
Nov 21 '08 #3

ChrisWang
P: 9
I found another solution to this problem.

I can use a name space for the scoping.

__main__.a will be referenced to a global variable.

Anyway, I think container is better.
Nov 21 '08 #4

Curtis Rutland
Expert 2.5K+
P: 3,256
Please enclose your posted code in [CODE] [/CODE] tags (See How to Ask a Question). Code tags preserve indention and uses a monospaced font.

This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

Please use [CODE] [/CODE] tags in future.

MODERATOR
Nov 21 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.