Search code examples
pythonreturn

why do i get "return outside function" eventhough my indentation is correct?


Does anyone know why I get an indentation error even though it (should) be correct?

while not stop:
    try:
        response += sock.recv(buffer_size)
        if header not in response:
            print("error in message format")
            return # this is where I get the error 
    except socket.timeout:
        stop = True

Error Code python3 ueb02.py localhost 31000 File "ueb02.py", line 40 return ^ SyntaxError: 'return' outside function make: *** [run] Error 1

edit: Thanks for the answers, @balderman's approach solved my problem. Thanks to everyone who contributed here :D


Solution

  • You can use return only if the code is part of a function.

    Use sys.exit() if you want to stop the flow of program.

    See https://python101.pythonlibrary.org/chapter20_sys.html#sys-exit