【发布时间】: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中有错字。
hi = 1
result = 0
def hello(x):
x = x + 10
result = x
helli(hi)
print(result)
为什么我的代码输出“0”而不是 11?
【问题讨论】:
helli 中有错字。
您需要为此使用关键字 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)
【讨论】: