【问题标题】:Function won't store a value函数不会存储值
【发布时间】:2019-11-24 20:12:12
【问题描述】:

我正在尝试编写一个带有函数的 Python 脚本。

下面的代码按预期工作,它打印 3。

def function(a,b):
  k = a+b
  print(k)

a = 1
b = 2
function(a,b)

但是当我像这样将 print 语句移到函数之外时,它就不起作用了。

def function(a,b):
  k = a+b

a = 1
b = 2
function(a,b)

print(k)  # -> NameError: name 'k' is not defined

关于如何在函数中不包含 print 语句并仍然让这段代码工作的任何想法?

【问题讨论】:

  • 请注意,“它不起作用”不是一个有用的问题陈述。在这种情况下,错误很明显,所以我已经为您添加了它,但是将来创建 minimal reproducible example 会很有帮助。
  • 顺便说一句,在函数内部和外部都有名为 ab 的变量是不好的做法,因为 shadowing

标签: python scope


【解决方案1】:

k是函数内部定义的局部变量。

案例一:直接退货:

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

案例 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

请阅读更多here

【讨论】:

  • 好的,但是返回 k不是更好吗?没有理由帮助初学者成功编写糟糕的代码。
  • 我同意@JohnColeman。这似乎不是 OP 想要或需要的。
  • @AlexanderCécile 我怀疑它 OP 想要的(也许不知道),尽管不应该鼓励他们有这样的愿望。另一方面,global 也有有效的用例,因此让他们意识到这一点并没有什么坏处。
  • 我同意退货声明。我已经编辑了我的答案
  • @JohnColeman 当然有有效的用例,但也应该说得很清楚。你说得对,我们无法确定 OP 想要什么。
【解决方案2】:

与其设置全局变量(全局变量通常不好),不如返回结果并打印出来?

类似

def function(a,b)
  return a+b

print(function(1,2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 2017-09-06
    • 2023-03-16
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多