Home > Enterprise >  Why does my variable change in the certain function/statement only in Python?
Why does my variable change in the certain function/statement only in Python?

Time:12-12

my variable won't update if I change it in a function. Here's the code:```

my_var = None
def func(string):
    if string == "Hello":
        my_var = string
        print(my_var) # prints 'Hello'

print(my_var) # prints None

How can I update my variable for all the script?

CodePudding user response:

First you need to actually call func, because for now, your code is same as

my_var = None
print(my_var)

So change to

my_var = None
func("Hello")
print(my_var)

Also, you need to tell your method to use the global my_var one, because if not it'll define a variable with the same name in the scope of the method, and the global one won't change

def func(string):
    global my_var
    if string == "Hello":
        my_var = string
        print(my_var)
  • Related