def func():
a = 1
print(a+12)
return a
func()
print(a) #this will not work. `a` is not bound to anything in this scope.
x = func()
print(x) #this will work
print(func()) #this also works
def func():
a = 1 # this line is not ever run, unless the function is called
print(a + 12)
print(a)
要使函数中的变量集符合您的要求,您可以尝试以下方法:
a = 0
print(a)
def func():
global a # when we use a, we mean the variable
# defined 4 lines above
a = 1
print(a + 12)
func() # call the function
print(a)
可以使用
return
语句将值传递到更高的范围结果:
请注意,该值没有绑定到变量在函数中的名称。您可以将它指定给任何您想要的对象,或者直接在另一个表达式中使用它
我认为您不能,因为变量“a”的作用域限制在函数func()中。如果在函数外部定义了“a”,则可以在函数外部调用该变量。如果您是python初学者(和我一样),请使用this。它帮助了我
PS:我可能错了,因为我也是python的初学者
在python中,作用域是函数、类主体或模块;只要有赋值语句
foo = bar
,它就会在赋值语句所在的范围内(默认情况下)创建一个新变量(名称)在外部范围内设置的变量在内部范围内可读:
在内部作用域中设置的变量在外部作用域中看不到。请注意,您的代码甚至没有设置变量,因为该行从未运行过
要使函数中的变量集符合您的要求,您可以尝试以下方法:
相关问题 更多 >
编程相关推荐