0

I have following code:

my_var=1
def a():  
    def b():
        my_var=2
    b()
    return my_var

print(a())

I'm trying to change the variable my_var in sub-function b(). The result should be 2 instead of 1. But in my code, it doesn't work. How can I solve this problem?

  • 2
    You could use `global` or better return the value from the function and assign it to your variable. – Maximilian Peters Apr 03 '21 at 14:00
  • oh great thank! I did not know that I also use global in sub-function Thanks! –  Apr 03 '21 at 14:11
  • Does this answer your question? [Python function global variables?](https://stackoverflow.com/questions/10588317/python-function-global-variables) – Czaporka Apr 03 '21 at 14:18
  • Yes, but I was not sure, if it's also for sub-functions. Thanks! –  Apr 03 '21 at 14:27

1 Answers1

0

global is the keyword used in python to access the actual variable which is present outside function try out the below code.

my_var=1
def a(): 
    def b():
        global my_var
        my_var = 2
    b()
    return my_var

print(a())