1

For example, I want to call a function LSE(n). And once I call LSE(5), I want n to be a callable by other functions as 5. I tried nesting the other functions accessing n inside LSE, but it could not access n too.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Samson
  • 1,336
  • 2
  • 13
  • 28
  • https://stackoverflow.com/questions/9242812/python-function-parameter-as-a-global-variable – ABO Baloyi Sep 30 '18 at 11:33
  • Possible duplicate of [Python function parameter as a global variable](https://stackoverflow.com/questions/9242812/python-function-parameter-as-a-global-variable) – Matthew Smith Sep 30 '18 at 11:36
  • While the question is similar, the accepted answer for above question does not help me. I want to let the user call a single function with several parameters, and several other functions will be called by the first function to do the computation needed with the parameters, before returning a single value to the user. I am unable to think of a way the return method can do that – Samson Sep 30 '18 at 13:40

2 Answers2

2

Between functions this can be achieved with the global keyword. This approach is usually frowned upon.

n = 0
def LSE(value):
    global n
    n = value

def second_func():
   global n
   print(n)

trying this out:

>>> LSE(5)
>>> second_func()
5

If you want to share values between functions, may I suggest encapsulating them in a class?

Anuvrat Parashar
  • 2,960
  • 5
  • 28
  • 55
  • Is there anyways to do the global thing without changing the name? I.e. I want to take my parameter make it a global variable retaining the same name (as opposed to here where value and n are named differently) – Samson Sep 30 '18 at 13:26
  • maybe. Why would you want to do that? – Anuvrat Parashar Sep 30 '18 at 15:46
0

"Is there anyways to do the global thing without changing the name? I.e. I want to take my parameter make it a global variable retaining the same name (as opposed to here where value and n are named differently)"

from: How to get the original variable name of variable passed to a function

"You can't. It's evaluated before being passed to the function. All you can do is pass it as a string."

What is doable is you can make your code always use a specific variable name, and within your function, declare it a global variable. That way you wouldnt even need to pass it as a parameter, but it would get affected every time you used the function; example:

def test_function ():

    global N

    N = N + 1

    print (N)

N = 5

test_function()
test_function()
test_function()

6 7 8

epattaro
  • 2,330
  • 1
  • 16
  • 29
  • I see, but the above method does not allow me to take in a parameter with name N still, but thanks for the clarification! – Samson Sep 30 '18 at 13:43