-1

I want function(x) to change the value of whatever global variable is put into it, say add one to the variable, like so:

>>> a = 1
>>> function(a)
>>> print(a)
2

I tried:

def function(x):
    global x
    x = x + 1

However, this returns a SyntaxError name 'x' is parameter and global...

aanonym
  • 15
  • 3
  • "change the value of whatever global variable is put into it"—This is not possible. The function does not receive the variable used when calling it. It only receives the value. – khelwood Jul 22 '20 at 10:10
  • it doesn't really make sense to pass the variable as an argument and also expect to change it in the local namespace. – Vishal Singh Jul 22 '20 at 10:11
  • You have an issue here because numbers are immutable, they are not modified, variables end up pointing to a different number, so if you have a variable pointing to a number you won't be able to change that number. There may be a deep way of modifying directly which memory direction a variable is pointing to but I would suggest you stay away from that – Adirio Jul 22 '20 at 10:11
  • There is one way this could be done if passing the variable name (`'x'`) instead of the variable itself(`x`): You can achieve this if you pass the variable name instead of the variable: `def function(var): globals()[var] += 1` – Adirio Jul 22 '20 at 10:23

1 Answers1

0
a=1 #global variable
def function():
    global a
    a=a+1 #operation on variable a
    return a
function()

is this answer your query?

user13966865
  • 448
  • 4
  • 13
  • Sorry, no. I said "whatever" global variable, hence I need the function to work for any variable put into it, not just 'a'. – aanonym Jul 22 '20 at 10:12