[Tutor] return, why do I need it?

Lie Ryan lie.1296 at gmail.com
Sun Dec 11 18:25:42 CET 2011


On 12/12/2011 01:38 AM, Pete O'Connell wrote:
> Hi I have been writing python code for a while now and I never return
> anything within any of my functions, I just (eg.) print stuff or make
> directories or update a log or what have you. When I look at other
> people's code they are always returning in their functions and I was
> wondering if someone could give me an example of when I would absolutely
> have to return something. The thing I don't like about returning is that
> when I unindent a function and try to run the code to inspect parts of
> it for debugging I always have to alter the code so as not to get the
> "return not inside a function error", so I will change the word
> "return" to "print" and in many cases that's the way I leave it. Anyone
> have any thoughts on this?

Functions returning a value is much more reusable than functions 
printing the value directly. For example, if you later decided that you 
want to store the calculation result in a file or display it in GUI or 
if you want to reuse the result for further calculation, you do not need 
to modify the function; you just need to modify the caller. And if you 
decided to create a GUI for your command line app, you can easily reuse 
functions returning a value but not when it printed them directly.



More information about the Tutor mailing list