【发布时间】:2018-02-01 17:13:58
【问题描述】:
这是一个为正整数 a 和 b 和 a <= b 求最大公约数的示例。我从较小的a 开始,一一减去,检查它是否是两个数字的除数。
def gcdFinder(a, b):
testerNum = a
def tester(a, b):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
testerNum -= 1
tester(a, b)
return tester(a, b)
print(gcdFinder(9, 15))
然后,我收到错误消息,
UnboundLocalError: local variable 'testerNum' referenced before assignment.
使用global testerNum后,成功在Spyder控制台显示答案3...
但在 pythontutor.com 中,它说 NameError: name 'testerNum' is not defined (link)。
Q1:在 Spyder 中,我认为 global testerNum 是一个问题,因为 testerNum = a 不在全局范围内。它在函数gcdFinder 的范围内。这个描述正确吗?如果是,Spyder 是如何给出答案的?
Q2:在pythontutor中,说最后一个截图,pythontutor中NameError问题如何解决?
Q3:为什么Spyder和pythontutor的结果有差异,哪个是正确的?
Q4:最好不要使用global方法吗?
--
更新:Spyder 问题是由于之前运行存储的值造成的,因此它已经定义为9。这使得global testerNum 工作。我已经删除了 Q1 和 Q3。
【问题讨论】:
-
不回答您的任何问题,我认为将 testerNum 解析为参数会更好,因此将定义函数
tester:def tester(a, b, testerNum) -
实际上是对您的问题 2 和 4 的回答:D
-
示例代码中
testNum不是global。尝试改用关键字nonlocal。这假设您使用的是 python3。
标签: python python-3.x scope spyder global-scope