How to change the value of a variable through function in Python?

4

How can I change the value of a variable through a function? Here's an example of what you'd like to do:

def func(t):
    t = 2 + 3

t = 7
func(t)
print(t)

The output of the print (t) function returns me the value 7 and not 5 as the desired, how can I make what was done in the function to be applied to the passed variable? Thanks in advance.

    
asked by anonymous 04.08.2017 / 22:46

2 answers

4

I do not think I understood the mechanism of the variable. Every variable has scope , it only exists where it was declared. Even if you have the same name and declared in different places, they are totally different variables, there is no point in messing with one expected and the other changing. At least this is true of variables with values with value semantics .

There are values that are stored in variables that have reference semantics. In this case, when you change the value of the object referenced by the variable this is valid for all references to that object, it is not that you are changing the value of another variable, but you are changing an object that has more than one variable pointing to it. It is obvious that access in all variables does not matter.

In this case that the variable has a value type the most obvious solution is to return the value you want. Even Python allows you to return more than one value.

def func(t):
    return 2 + 3

t = 7
t = func(t)
print(t)

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

Another solution is to encapsulate this value into a type by reference as a list or dictionary, but it sounds like gambiarra, I would not do that.

There is also a global variable, but do not even think about using it, it's almost always a mistake. Lets use it when you do not have the best solution and know a lot what you're doing. Global scope is a problem .

    
04.08.2017 / 23:10
1
def func(a):
    global x
    x = 2 + 3

x = 7
func(x)
print(x)
    
18.04.2018 / 18:06