Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading