如果你有如下的python代码:
thing = "string"
def my_func(variable):
variable = input("Type something.")
my_func(thing)
print(thing)那么变量'thing‘将只返回'string’,而不是新输入的内容。如何在不列出实际变量名的情况下对其进行更改?
发布于 2018-01-22 00:42:09
,你在变量的作用域上有问题。
在这里,在函数中将thing作为变量没有任何用处,因为在明确定义函数仅更改thing的值之前,不能通过调用任何函数来更改它。
您可以通过一种方式将其定义为:
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'但上述方法仅适用于thing变量。而不是传递给它的任何其他变量,但像下面这样的函数可以处理所有事情。
thing = "string"
def my_func():
a = input("Type something."))
return a
>>>thing = my_func()
>>>Type something: Hello world
>>>print(thing)
>>>'Hello world'https://stackoverflow.com/questions/48369097
复制相似问题