我正在尝试编写一个带有函数的 Python 脚本。
下面的代码按预期工作,它打印 3。
def function(a,b):
k = a+b
print(k)
a = 1
b = 2
function(a,b)
Run Code Online (Sandbox Code Playgroud)
但是当我像这样将打印语句移到函数之外时,它将不起作用。
def function(a,b):
k = a+b
a = 1
b = 2
function(a,b)
print(k) # -> NameError: name 'k' is not defined
Run Code Online (Sandbox Code Playgroud)
关于如何在函数中没有打印语句并仍然使此代码工作的任何想法?
k 是在函数内部定义的局部变量。
案例1:只需返回它:
def function(a,b):
k = a+b
return k # just return, does not make it global
a = 1
b = 2
k = function(a,b)
# 3
print(k) # variable was returned by the function
Run Code Online (Sandbox Code Playgroud)
案例 2:使其成为全球性的:
def function(a,b):
global k #makes it global
k = a+b
function(a,b)
print(k) # it is global so you can access it
Run Code Online (Sandbox Code Playgroud)
请在这里阅读更多
与其设置一个全局变量(全局变量往往不好),为什么不返回结果并打印出来呢?
就像是
def function(a,b)
return a+b
print(function(1,2))
Run Code Online (Sandbox Code Playgroud)