SyntaxError: ‘return’ outside function. scoping problem [closed]

i’m trying to get this to work but no matter how i indent it, it wouldn’t compile giving me this error.

def gcdIter(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
testVal = min(a, b)
ans = 0
while testval > 0:
    if max(a, b) % testval == 0:
        ans = testVal
    else:
        testval -= 1
    return ans 

Answer

There is an issue in the indentation of the function gcdIter The code block should come under the same indentation level as docstrings,

Also the testVal is referenced incorrectly in the while block.

updated one

def gcdIter(a, b):
  '''
  a, b: positive integers
  returns: a positive integer, the greatest common divisor of a & b.
  '''
  testVal = min(a, b)
  ans = 0
  while testVal > 0:
   
    if max(a, b) % testVal == 0:
      ans = testVal
    else:
      testVal = -1
  return ans 

If you’re looking to find the GCD of two numbers, your code will run infinitely due to this condition while testVal > 0:

If you’re looking to find gcd of two numbers using iteration, this should help

def gcdIter(a, b):

    while (a != b):
        if (a > b):
            a = a - b
        else:
            b = b - a
    return a