How to modify a variable within a definition without globalizing the variable?

Asked

Viewed 53 times

1

I need to modify a variable within a definition without globalizing the variable because then I can use the same definition with different variables.

I’ve tried the following code:

>>> n = 0
>>> def f(mmm):
        mmm = 1
        return mmm

>>> f(n)
>>> 1
>>> print(n)
>>> 0

Even after executing the setting, the variable n continues with the value of before, which I can do?

  • 2

    I think it is best that you assign the return of function f to variable n. That is n = f(n)

1 answer

1

In fact, without using global variable, it is not possible to do what you want.

Because if I do:

def f(mmm):
    mmm = 1
    return mmm

f(10)

Note that I called the function by passing a value directly instead of using a variable (f(10)) - if it were possible to modify the variable from outside, what would be changed in that case? The 10? Makes no sense.

Of course some languages allow the variable value to be changed within the function, but Python was not done like this.

To documentation cites some ways around this. In your case, the simplest seems to be to simply take the return of the function and assign it in the variable itself:

n = f(n)

To supplement the subject, I suggest you read here, here and here.

  • thank you very much!

  • @If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem

Browser other questions tagged

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