SyntaxError: 'return' outside function keeps happening (Python). Any idea?

Viewed 18

The error is at the bottom of the code.

def decimalToRep(num,base):
result = ""
while(num>0):
    rem = num % base
   if rem in range(10):
   result += str(rem)
else:
    result += chr(65+(rem%10))
num = num // base
result = result[::-1]
if(result == ""): 
return ''
return result
def main():
"""Tests the function."""
print(decimalToRep(10, 10))
print(decimalToRep(10, 8))
print(decimalToRep(10, 2))
print(decimalToRep(10, 16))

#The entry point for program execution
if __name__ == "__main__":
    main()

File "/root/sandbox/convert.py", line 14 return '' ^^^^^^^^^ SyntaxError: 'return' outside function

1 Answers

This error is because the indentation of your Python script is wrong. Python uses the indentation to determine where your blocks of code begin and end - such as the while loop and the if statement.

See https://www.w3schools.com/python/gloss_python_indentation.asp for some examples.

Your function should be indented as:

def decimalToRep(num,base):
    result = ""
    while(num>0):
        rem = num % base
        if rem in range(10):
            result += str(rem)
        else:
            result += chr(65+(rem%10))
        num = num // base
    result = result[::-1]
    if(result == ""): 
        return ''
    return result
Related