0

I'm tinkering around with Python. I have two functions. The first one calls the second, and from the second I am trying to get the value of a local variable within the first, like so:

def b():
    local_var = 8
    a()

def a():
    #get b::local_var here?

I understand that it is possible in python to print out the stack, but I was wondering about accessing the variables and memory within those functions. Is this even possible?

APerson
  • 8,140
  • 8
  • 35
  • 49
Oldfrith
  • 51
  • 5
  • 2
    possible duplicate of [Use of "global" keyword in Python](http://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – APerson Nov 21 '14 at 17:05
  • I have found another solution, sorry if what I was asking sounds weird. – Oldfrith Nov 21 '14 at 19:11

2 Answers2

0

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

So in this case you can use 2 way : 1. define a global variable :

>>> def b():
...     global local_var
...     local_var=8
...     a()
... 
>>> def a():
...  print local_var
... 
>>> a
8

2.pass the variable in a() as its argument :

>>> def b():
...     local_var=8
...     a(local_var)
... 
>>> def a(arg):
...  print arg
... 
>>> a
8
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

yes you can, just pass the variable in the function

def b():
   local_var = 8
   a(local_var) #1

def a(LV): #2
   print LV

1

you passed the variable

2

created a new variable LV and assigned the local_var value to LV

abdulla-alajmi
  • 491
  • 1
  • 9
  • 17