Python Forum
How to change global variable in function? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to change global variable in function? (/thread-14001.html)



How to change global variable in function? - dan789 - Nov-10-2018

Hello, I need your help, I have to make program containing changing a global variable using a function. But, without using "global". Do you have any idea how can I get around this?

Thanks in advance.


RE: How to change global variable in function? - buran - Nov-10-2018

your function should return value and you will assign the returned value to the variable you want to change. The function may or may not take arguments.

def multiply(number):
    return number*3

my_var = 2
my_var = multiply(my_var)
print(my_var)
in this example I pass my_var as argument to the function, but that's not mandatory nor always the case


RE: How to change global variable in function? - ichabod801 - Nov-10-2018

I'm confused. Do you need to change a global variable to the result of a function? Then you would just return the value from the function, and assign that to the global variable:

SPAM = 1

def eggs():
    return 2

SPAM = eggs()
Or is your assignment to so the change to the global variable within the function without using the global statement?


RE: How to change global variable in function? - dan789 - Nov-10-2018

Thank you very much. :) All I need to do with this is a global variable type list and a function, which gets data and then save list into this variable. So, when I understand that correctly, all I have to do is creating a local variable type list inside a function, get data to this list, and this local variable make as return of that function and assign it to the global one, am I right?


RE: How to change global variable in function? - buran - Nov-10-2018

that would be the better approach.
However you should know that list is a mutable type, and you can change the list elements inside the function without using global
my_list = [1, 2]
def change_list():
    my_list[0] = 3
    my_list[1] = 4

change_list()
print(my_list)

def change_list1(some_list):
    some_list[0] = 10
    some_list[1] = 11

change_list1(my_list)
print(my_list)

def change_list2():
    return [5, 6]

my_list = change_list2()
print(my_list)
Output:
[3, 4] [10, 11] [5, 6]



RE: How to change global variable in function? - dan789 - Nov-10-2018

@buran that´s a good reminder, thanks for that. I have not realised this before.

Thanks for detailed explanation to both of you. :)