+ 3
Python confusement
how to change variable from function? im currently think something like this: nice = 1 def okay: nice += 1 but its become an error
7 Answers
+ 5
You can do it with list :
def add_one(l):
l[0]+=1
x = [5]
add_one(x)
print(x[0])
But ... either list or global are bad practice. Best way stays :
def add_one(x):
return x+1
x = 5
x = add_one(x)
+ 2
i cant decide the best answer.you all gave me good answer
+ 2
thats a error
because
it will be
nice=1
def okay() :
nice+=1
+ 2
or u can do directly...
num=1
def okay():
return num+1
+ 2
If you must choose, it'd be @Hatsy's, since it precisely addresses your issue.
To be more concrete, this is about the scope rules of Python, where, in general, inner scopes operations can't change the name bindings in outer scopes without specific statements (i.e. global and nonlocal). In-place operators of immutable types must create new objects and so, as explained in the aforementioned SO thread, they're equivalent to rebinding the new object to an unbound variable.
If you want to know more about this (or kinda the TL;DR of this comment), good places to start are,
the very Python docs https://docs.python.org/3/reference/executionmodel.html#naming-and-binding ,
this SO thread https://stackoverflow.com/q/291978 especially Rizwan and Antti's answers,
and the first result I got after a quick Google search http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html .
+ 2
Another stack overflow post that may answer your question :
https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference/986145#986145