0

If you have python code like this:

thing = "string"
def my_func(variable):
    variable = input("Type something.")

my_func(thing)

print(thing)

Then the variable 'thing' will just return 'string' and not what the new input is. How can I change it without listing the actual variable name?

AquaAvis
  • 55
  • 6
  • You shuld return a value from your function and assign it to the variable. `thing = my_func()` – James Jan 21 '18 at 16:38
  • The parameters that you are passing by value, you must return the value and assign it again to the variable: `thing = "string" def my_func(variable): variable = input("Type something.") return variable thing = my_func(thing) print(thing)` – eyllanesc Jan 21 '18 at 16:39
  • Possible duplicate of [Python: functions to change values 'in place'?](https://stackoverflow.com/questions/22338671/python-functions-to-change-values-in-place) – eyllanesc Jan 21 '18 at 16:55

1 Answers1

0

You have problems with scopes of variables.

Taking in the thing as a variable inside your function isn't any useful here as it can't be changed just by calling any function until you specifically define the function to change only the value of thing.

You can define it in one way as:

thing = "string"
def my_func():
    global thing #As thing has a global scope you have to tell python to modify it globally
    thing = input("Type something:")
>>>my_func()
>>>Type something: hello world
>>>print(thing)
>>>'Hello world'

But the above method will only work for the thing variable. And not on any other variables passed to it, but a function like below will work on everything.

thing = "string"
def my_func():
    a = input("Type something."))
    return a
>>>thing = my_func()
>>>Type something: Hello world
>>>print(thing)
>>>'Hello world'
Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27
  • It is not appropriate to use the name of a function as a variable: `input = input("Type something."))`. what is `a`? – eyllanesc Jan 21 '18 at 16:51
  • @eyllanesc Sorry, I corrected it, any improvements you can suggest? – Ubdus Samad Jan 21 '18 at 16:54
  • 2
    The use of global variables can bring problems that are difficult to track, so I avoid using them and recommend them unless the variable is unique, and I do not recommend it for beginners because they tend to abuse them. :D – eyllanesc Jan 21 '18 at 17:25