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

Asked

Viewed 4,695 times

4

How can I change the value of a variable through a function? Here’s an example of what I’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 desired, how can I make it done in the function to be applied to the passed variable? Thanks in advance.

2 answers

4


I don’t think you understand the mechanism of the variable. Every variable has scope, It only exists where it was declared. Even if you have the same nom and declared in different places, they are totally different variables, it is useless to touch one waiting for the other to be changed. At least it is so in 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 holds 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 the access in all variables is equal.

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

def func(t):
    return 2 + 3

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Another solution is to encapsulate this value in a type by reference as a list or dictionary, but it seems quite gambiarra, I would not do this.

There’s also a global variable, but don’t even think about using it, it’s almost always a mistake. Leave to use when you have no better solution and know a lot what you are doing. State with global scope is a problem.

  • func(t) this t is not used correctly, I think it is nice to put a code with its use. In python has global variable?

  • @Brunoh. I put on it, ie not to use.

  • Thank you for answering, for correction and tip.

0

def func(a):
    global x
    x = 2 + 3

x = 7
func(x)
print(x)
  • 2

    Although it works, it’s a terrible solution. Importing objects from the global scope in this way can generate undesirable side effects and very difficult to identify in maintenance. Maniero quoted in his reply a link about this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.