Reputation: 1
I have created the following sample program to demonstrate what I'm trying to do:
name = "d"
def namechange (name):
global name
name = "Henry"
return name
print name
The errors that is produced:
SyntaxError: name 'name' is local and global
I understand that the name variable is local and global, but I am new to this and do not know how to resolve this issue. Please help
Upvotes: 0
Views: 161
Reputation: 22953
Python considers function parameters as local variable. So since your function is accepting a parameter also named name
, Python now considers name
to be a local variable:
>>> global_variable = 0
>>> def foo(global_variable): # your creating a local variable here.
global global_variable
SyntaxError: name 'global_variable' is parameter and global
>>>
The fix is to remove name from your functions parameters. That way, Python will see name
as a global variable:
name = "d"
def namechange (): # remove name
global name
name = "Henry"
print name
However, you should avoid using globals when you can. In this case, it would be a better solution to pass name as a parameter to your function, and let the caller deal with updating the variable:
name = "d"
def namechange (name):
name = "Henry"
return name
new_name = namechange(name)
print new_name
Upvotes: 1
Reputation: 387507
def namechange (name):
This introduces a local variable name
.
global name
Yet this also introduces the global variable name
in the same scope.
Hence the syntax error that name
is both local and global. In order to fix this, you have to either remove the local variable, or the global variable. In your case, you could do both.
You could either remove the local variable and just make the function modify the global variable, like this:
def namechange ():
global name
name = "Henry"
In that case, you don’t actually need to return anything, since this already modifies the global variable.
Or you could remove the global variable, and make this function just return the new value:
def namechange (name):
name = "Henry"
return name
In that case, it would be the caller’s responsibility to update the variable from the outer scope:
name = "d"
new_name = namechange(name)
print(new_name) # Henry
Upvotes: 1