Question about "global" statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ChrisWang
    New Member
    • Nov 2008
    • 9

    Question about "global" statement

    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:

    Code:
    def foo (a):
        global p
        global a
        p = a + 3  #here "a" will be reference to the global one
        
    a = 1
    p = 0
    foo (a)
    print a, p
    When I executed this script, Python said "SyntaxErro r: 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!
  • Smygis
    New Member
    • Jun 2007
    • 126

    #2
    If you have to use global variables my favorite way is to crate a container for the global variables, like this:

    Code:
    >>> class gv: pass
    ... 
    >>> def foo():
    ...     gv.p = gv.a + 3
    ... 
    >>> gv.p, gv.a = 0, 1
    >>> foo()
    >>> print gv.a, gv.p
    1 4
    >>>
    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.
    Code:
    >>> def bar(a):
    ...     global a
    ...     print a
    ... 
    SyntaxError: name 'a' is local and global
    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.

    Comment

    • ChrisWang
      New Member
      • Nov 2008
      • 9

      #3
      Good suggestion! Thanks!

      Comment

      • ChrisWang
        New Member
        • Nov 2008
        • 9

        #4
        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.

        Comment

        • Curtis Rutland
          Recognized Expert Specialist
          • Apr 2008
          • 3264

          #5
          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

          Comment

          Working...