+ 1
[SOLVED] Can anyone please explain me why doesn't the value of x change, while I'm using this method?
def add_something(x): x += "something" x = "" add_something(x) print(x)
8 ответов
+ 3
one way to correct it would be like this:
def add_something(x):
return x += "something" # added return line so the function will return a value
x = input() # converted blank variable to be input variable.
result=add_something(x) # added variable to store return value from function. you can also print(add_something(x)) instead of storing value.
print(result) # print value from stored variable.
+ 6
please allow me to give my personal opinion to what is discussed here about this task:
the preferred and most simple and pythonic way is the ones mentioned:
def add_something(x):
return x + "something"
x = input()
result = add_something(x)
print(result)
▪︎the code is easy to read, to understand and to maintain. all the other suggestions are not wrong and they may also work.
BUT:
▪︎using global variables is not a preferred programming style, there may be some reasons to use them, but not in this case.
▪︎global variables contradict the principle of hiding data as much as possible in order to prevent unauthorized or unwanted access or modifications.
we have had many discussions in the past about using global variables. You love global variables or you don't love them.
+ 2
Andrew Choi is a good solution, but I found a better solution:
def add_something(x):
globs = dict(globals())
for name in globs:
if globs[name] is x:
globals()[name] += "something"
o = ""
add_something(o)
print(o)
+ 2
Calvin Thomas I don't know. It worked for me.
+ 1
Because here X is passed to the function by value not by reference.
+ 1
So, how can I change the value of x using a method?
+ 1
Αλέξανδρος its all good as long as you get the answer you need. i dont work with globals all the much, but i have heard you need to be careful with them. all in all, glad you were able to find a solution you liked. 👍
+ 1
Αλέξανδρος You can't make a function parameter global. The only remaining way is to return the value. Another way is to do something like this:
result = ""
def add(x):
global result
result = x + "something"
add("test")
print(result)
# Hope this helps