+4 votes
in Programming Languages by (74.2k points)

How can I access a local variable defined inside a function outside the function?

E.g.

 def myfun1():

    v = 25

If I print the value of v outside the function, it should print 25.

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Using the keyword "global", you can change the scope of a variable from local to global, and then you can access it outside the function.

E.g.

The following code will print v =25 although the print statement is outside the function.

def myfun1():
   global v
   v = 25

myfun1()
print(v)


...