+4 votes
in Programming Languages by (14.6k 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

0 votes
by (25.6k points)

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)

...