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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sairam

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

    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

  • 7stud

    #2
    Re: Can we make a local variable in a function as global variable???

    On Apr 5, 3:19 am, "sairam" <sai...@gmail.c omwrote:
    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)
    -----------

    Comment

    • Steve Holden

      #3
      Re: Can we make a local variable in a function as global variable???

      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

      Comment

      Working...