Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, if a function doesn't have a return statement, what does it return?

Given this example function:

def writeFile(listLine,fileName):
    '''put a list of str-line into a file named fileName'''
    with open(fileName,'a',encoding = 'utf-8') as f:
        for line in listLine:
            f.writelines(line+'\r\n')
    return True

Does this return True statement do anything useful?

What's the difference between with it and without it? What would happen if there were no return function?

like image 614
zds_cn Avatar asked Mar 12 '13 06:03

zds_cn


People also ask

What does a function return if there is no return statement?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

What does a return statement do in Python?

A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed.


3 Answers

If a function doesn't specify a return value, it returns None.

In an if/then conditional statement, None evaluates to False. So in theory you could check the return value of this function for success/failure. I say "in theory" because for the code in this question, the function does not catch or handle exceptions and may require additional hardening.

like image 129
Travis Bear Avatar answered Sep 23 '22 18:09

Travis Bear


The function always returns None if explicit return is not written.

like image 30
GodMan Avatar answered Sep 22 '22 18:09

GodMan


If you have the return True at the end of the function, you can say stuff like: a=writeFile(blah, blah)

However, because it will always be True, it is completely pointless. It would be better to return True if the file was written correctly, etc.

If you don't explicitly return anything, the value will be None

like image 41
Will Richardson Avatar answered Sep 23 '22 18:09

Will Richardson