【问题标题】:My variables updated in a function don't work outside the function [duplicate]我在函数中更新的变量在函数之外不起作用[重复]
【发布时间】:2021-06-25 19:49:00
【问题描述】:
hi = 1
result = 0
def hello(x):
    x = x + 10
    result = x
helli(hi)
print(result)

为什么我的代码输出“0”而不是 11?

【问题讨论】:

  • 欢迎来到 SO。您在helli 中有错字。

标签: python function variables


【解决方案1】:

您需要为此使用关键字 global。然后在函数内部编辑的值实际上会从函数外部影响变量。 这不是推荐的方法。

hi = 1
result = 0

def hello(x):
    global result
    x = x + 10
    result = x

hello(hi)
print(result)

然而,推荐的方法是返回这样的值:

def hello(x):
    return x + 10

hi = 1
result = 0
result = hello(hi)
print(result)

【讨论】:

猜你喜欢
  • 2015-02-26
  • 2012-12-10
  • 2021-10-05
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 2017-05-07
  • 1970-01-01
相关资源
最近更新 更多