1

How can I change the values of variables inside a function and keep those values outside the said function? For example, here:

string = 'values'
num1 = 6
num2 = 8

def change():
    string = 'gone'
    num1 = 0
    num2 = 0

print(num1, num2, string)

I'd like "0 0 gone" to be displayed instead of "6 8 values".

trycon29
  • 13
  • 2

2 Answers2

4

Variables that are defined outside of functions (in the global area) are called global variables. When you use a global variable inside a function, you are actually creating a local variable that is different from the global one. To change a global variable from inside a function, you should say that you want to refer to the global variable.

def change():
    global string, num1, num2
    string = 'gone'
    num1 = 0
    num2 = 0

Now if you call change, they will change globally. However this is not a good approach, it's better that you keep functions as a black box that don't have any side effect; So it's better that you do it this way:

def change():
    s = 'gone'
    n1 = 0
    n2 = 0
    return s, n1, n2

string, num1, num2 = change()
aaronn
  • 448
  • 1
  • 6
  • 16
0

First of all, you have not called the function and therefor everything inside would not be executed. Secondly, all the variables in your function are local to that on function. So use the global keyword inside the function to make it public.

string = 'values'
num1 = 6
num2 = 8

def change():
    global string,num1,num2
    string = 'gone'
    num1 = 0
    num2 = 0
change()
print(num1, num2, string)
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44