return statement in functions

hokieghal99 hokiegal99 at hotmail.com
Tue Dec 23 08:48:39 EST 2003


Peter Otten wrote:
> 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.

Yes, I see this now. It makes a lot of sense. In an earlier reply from 
Francis, it was made clear to me that functions work best when they do 
one thing well and when it's evident what they are attempting to do. By 
taking this approach to defining them, functions are very modular and 
easier to comprehend, no? So, they can then return their value to 
another function that maybe was written to print the information nicely 
or whatever. Is that a good way of thinking about functions?





More information about the Python-list mailing list