+ 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)

24th Jun 2021, 5:39 AM
Αλέξανδρος
Αλέξανδρος - avatar
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.
24th Jun 2021, 6:11 AM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 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.
24th Jun 2021, 3:18 PM
Lothar
Lothar - avatar
+ 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)
24th Jun 2021, 6:19 AM
Αλέξανδρος
Αλέξανδρος - avatar
+ 2
Calvin Thomas I don't know. It worked for me.
24th Jun 2021, 9:14 AM
Αλέξανδρος
Αλέξανδρος - avatar
+ 1
Because here X is passed to the function by value not by reference.
24th Jun 2021, 5:52 AM
TOLUENE
TOLUENE - avatar
+ 1
So, how can I change the value of x using a method?
24th Jun 2021, 5:54 AM
Αλέξανδρος
Αλέξανδρος - avatar
+ 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. 👍
24th Jun 2021, 6:34 AM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 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
24th Jun 2021, 9:11 AM
Calvin Thomas
Calvin Thomas - avatar