Here's an example to find the greatest common divisor for positive integers a
and b
, and a <= b
. I started from the smaller a
and minus one by one to check if it's the divisor of both numbers.
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))
Then, I got error message,
UnboundLocalError: local variable 'testerNum' referenced before assignment
.
After using global testerNum
, it successfully showed the answer 3
in Spyder console...
but in pythontutor.com, it said NameError: name 'testerNum' is not defined
(link).
Q1: In Spyder, I think that the global testerNum
is a problem since testerNum = a
is not in global scope. It's inside the scope of function gcdFinder
. Is this description correct? If so, how did Spyder show the answer?
Q2: In pythontutor, say the last screenshot, how to solve the NameError problem in pythontutor?
Q3: Why there's difference between the results of Spyder and pythontutor, and which is correct?
Q4: Is it better not to use global
method?
--
UPDATE: The Spyder issue was due to the value stored from previous run, so it's defined as 9
already. And this made the global testerNum
work. I've deleted the Q1 & Q3.