[英]Function won't store a value
I am trying to write a Python script with a function.我正在尝试编写一个带有函数的 Python 脚本。
The code below works as expected, it prints 3.下面的代码按预期工作,它打印 3。
def function(a,b):
k = a+b
print(k)
a = 1
b = 2
function(a,b)
But when I move the print statement outside the function like this, it won't work.但是当我像这样将打印语句移到函数之外时,它将不起作用。
def function(a,b):
k = a+b
a = 1
b = 2
function(a,b)
print(k) # -> NameError: name 'k' is not defined
Any ideas on how to not have the print statement inside the function and still get this code to work?关于如何在函数中没有打印语句并仍然使此代码工作的任何想法?
k
is a local variable defined inside the function. k
是函数内部定义的局部变量。
Case 1: Just return it:案例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
Case 2: Make it global:案例 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
Instead of setting a global variable (global variables are often bad), why not return the result and print it?与其设置一个全局变量(全局变量往往不好),为什么不返回结果并打印出来呢?
Something like就像是
def function(a,b)
return a+b
print(function(1,2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.