Can we make a local variable in a function as global variable???

Discussion in 'Python' started by sairam, Apr 5, 2007.

  1. sairam

    sairam Guest

    I have some local variables defined in one method and Can I make those
    variables as global variables? If so , can any one explain me how can
    I do that


    Thanks,
    Sairam
     
    sairam, Apr 5, 2007
    #1
    1. Advertising

  2. sairam

    7stud Guest

    On Apr 5, 3:19 am, "sairam" <> wrote:
    > I have some local variables defined in one method and Can I make those
    > variables as global variables? If so , can any one explain me how can
    > I do that
    >
    > Thanks,
    > Sairam

    -----------
    num = None

    def f1():
    global num
    num = 30

    def f2():
    print num


    f1()
    f2()
    -----------
    You can read from a global variable, but to assign to one, you have to
    declare its name in a global statement on the first line of the
    function.

    A better way:
    ------------
    def f1():
    num = 30
    return num

    def f2(x):
    print x

    result = f1()
    f2(result)
    -----------
     
    7stud, Apr 5, 2007
    #2
    1. Advertising

  3. sairam

    Steve Holden Guest

    Collin Stocks wrote:
    > As for me, I find this problem annoying, but easy to solve. My solution is:
    >
    > >>> this=__import__(__name__)

    >
    > To set global variable spam to 4, I say:
    >
    > >>> this.spam=4

    >
    > This always works, and is much more convenient than:
    >
    > >>> global spam
    > >>> spam=4

    >
    > and then worry about local variables also named spam.
    >

    That's truly horrible. And what if you have a local variable called "this"?

    regards
    Steve
    --
    Steve Holden +44 150 684 7255 +1 800 494 3119
    Holden Web LLC/Ltd http://www.holdenweb.com
    Skype: holdenweb http://del.icio.us/steve.holden
    Recent Ramblings http://holdenweb.blogspot.com
     
    Steve Holden, Apr 5, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. karim
    Replies:
    1
    Views:
    791
    George Ter-Saakov
    Jun 26, 2003
  2. Patrick Hoffmann
    Replies:
    3
    Views:
    2,919
    Christian Jan├čen
    Aug 8, 2003
  3. Mohanasundaram
    Replies:
    44
    Views:
    1,108
    Keith Thompson
    Aug 24, 2004
  4. Sullivan WxPyQtKinter
    Replies:
    10
    Views:
    706
    Antoon Pardon
    Nov 8, 2007
  5. Daniel Oberski
    Replies:
    9
    Views:
    828
Loading...

Share This Page