Page 123 -
P. 123
don't repeat yourself
Q: The return() command is just like print(), except nothing Q: What happens if the function omits the return()
appears on screen, right? command? Does each function have to have one?
A: Well... sort of. The print() command is designed A: No, the use of return() is not required. In fact, the
to display (or output) a message, typically on screen. The current version of your get_price() function doesn’t use
return() command is designed to allow you to arrange for a return() at all. But, your function feels like it gives you
function you write to provide a value to your program. Recall the something because it prints the current price on screen. When the
use of randint() in Chapter 1: a random number between return() command is omitted, a function returns a special no
two values was returned to your code. So, obviously, when value. In Python, this value is called None.
providing your code with a random number, the randint()
function uses return() and not print(). In fact, if Q: So, just to be clear, using return() is optional?
randint() used print() instead of return(), it
would be pretty useless as a reusable function. A: Yes, it is.
Q: So, it’s a case of return() letting a function give you Q:
something back? Does return() always come at the end of the function?
A: Usually, but this is not a requirement, either. The
A: Yes, that’s it, exactly. return() can appear anywhere within a function and, when it
Q: I’m not sure I’m convinced about using functions. Isn’t is executed, control returns to the calling code from that point in the
using copy’n’paste quick and easy? function. It is perfectly reasonable, for instance, to have multiple
uses of return() within a function, perhaps embedded
with if statements which then provide a way to control which
A: No, using copy’n’paste is quick and dirty, with the emphasis return() is invoked when.
on the “dirty.” When you need to repeatedly use some code, it’s
always better to create a function to contain and name that code. Q:
You then call (or invoke) the function as needed. If you later decide Can return() send more than one result back to the
to change how the repeated code works, it’s a no-brainer to change caller?
the code in the function once. If, instead, you “quickly” performed
copy’n’paste five times, that’s five changes you now have to make, A: Yes, it can. return() can provide a list of results to the
and the chance of you missing one change or making a mistake are calling code. But, let’s not get ahead of ourselves, because lists are
actually pretty high. So, don’t copy’n’paste! not covered until the next chapter. And there’s a little bit more to
Q: So, using a function lets you share the repeated code in learn about using return() first, so let’s read on and get back
to work.
a controlled way?
A: Yes, it does. There’s also a guiding principle among
prgrammers known as DRY: Don’t Repeat Yourself. Using functions
lets you keep your code DRY.
88 Chapter 3