return statement in functions

Peter Otten __peter__ at web.de
Tue Dec 23 04:17:56 EST 2003


hokiegal99 wrote:

> I was told earlier (w/o explanation) that functions should return
> something. I was under the impression that it was OK with Python to
> leave the return statement off. Could someone enlighten me on why or
> why not to use a return statement when defining functions? Below is
> the bit of code I was told should return something:
> 
> def fs_object_count(path):
>    file_count = 0
>    dir_count = 0
>    for root, dirs, files in os.walk(path):
>       file_count += len(files)
>       dir_count += len(dirs)
>    print "Number of Files Examined: ", file_count
>    print "Number of Folders Examined: ", dir_count
>    print "Total Number of FS Objects:", file_count + dir_count

I think I was the guy who told that. I did not mean that you should always
add an explicit return statement, you just posted a slightly different
function

[hokiegal99 in earlier post]

> def fs_object_count(path):
>     file_count = 0
>     dir_count = 0
>     for root, dirs, files in os.walk(path):
>        for fname in files:
>           file_count += len(fname)
>        for dname in dirs:
>           dir_count += len(dname)
> fs_object_count()


which attempted to calculate file and dir count but did neither return these
values nor print them. Thus the file_count and dir_count were lost and the
function useless.
 
As to the advantage of returning the result instead of printing it, Francis
Avila has already covered that.

Peter






More information about the Python-list mailing list