I'm trying to do something like this:
def func(varname):
varname = 1
func(x)
print(x)
But I get NameError: name 'x' is not defined
I'm trying to do something like this:
def func(varname):
varname = 1
func(x)
print(x)
But I get NameError: name 'x' is not defined
You need to declare the thing you are putting into the function as a parameter. You should also actually do something with the value you are changing in the method.
In your example
def func(varname):
varname = 1
return varname #Return whatever you do to the input
x=3
x =func(x) #Do something with the value returned from your method
print(x)
No, the syntactical construct you seem to be interested in is not possible. The reason is that function parameters are copies of the value (or reference) of the variable you pass in. Changing the value (or reference) of varname
cannot change the value (or reference, for mutables) of x
.
Now, the behavior that you want is totally possible. As a general rule, in order to have a function create a value and then assign that value to a variable name of your choice you use a return
statement:
def funcname():
return 1
x = funcname()
print(x)
Mostly the information you get back from a function is what is given in the return value. It's possible, even common, for functions to make changes in mutable data structures that they are passed (e.g. a list
), especially where this is capturing state information or updating on the basis of other information handled by the function. And if you rearrange the contents of a list, the list elements will certainly have different values when the function exits.
Certainly you could do this:
def square_it(varname):
return varname*varname
x = square_it(3)
print(x)
giving output of 9
, of course. You can also assign x
to something else so that they now both have the same value
y = x
x = square_it(y)
which in some senses "changes the name" of what is referring to the value 9
to y
, and moves x
on to refer to something else.