+ 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

31st Aug 2017, 11:38 AM
Kevin AS
Kevin AS - avatar
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)
31st Aug 2017, 11:58 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
i cant decide the best answer.you all gave me good answer
31st Aug 2017, 12:06 PM
Kevin AS
Kevin AS - avatar
+ 2
thats a error because it will be nice=1 def okay() : nice+=1
31st Aug 2017, 2:12 PM
sayan chandra
sayan chandra - avatar
+ 2
or u can do directly... num=1 def okay(): return num+1
31st Aug 2017, 2:14 PM
sayan chandra
sayan chandra - avatar
+ 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 .
31st Aug 2017, 10:13 PM
Edgar Garrido
Edgar Garrido - avatar
+ 2
1st Sep 2017, 12:36 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar