Reputation: 6284
An exercise on Codeacademy calls for creating code where a cube
function return
s the variable cubed
.
Then, when that function is called by the function by_three
, the authors suggest using another return
:
Make sure both functions return their values rather than printing them, and that both branches of the
if/else
statement inby_three
havereturn
statements in them.
The code, which is accepted as a correct answer, is:
def cube(n):
cubed = n**3
return cubed
def by_three(n):
if n % 3 == 0:
return cube(n)
else:
return False
Why do there need to be two instances of return
? First in cube
, and then again in if
for by_three
. Shouldn't the former be enough?
Or does the duplication help the code execute, and why? Can it be harmful?
Upvotes: 1
Views: 133
Reputation: 60004
If a function does not return anything, it defaults to returning None
.
Your cube
function, instead of printing the result, returns the result so it can be used elsewhere. If it were just print cubed
instead of return, then return cube(n)
would be equivalent to return None
, and this isn't what you want. Because return
returns (or in this case, assigns) the value to a variable.
In your by_three
function, it is useful to have the else: return False
, because, as mentioned above, it will otherwise return None
. This might not be helpful, because you may need the value False
to determine something else later in your code. The reason you were asked to put the return
s in the if/else was because that was what Codecademy wanted you to do :p. It's probably not going to be useful for you later during Codecademy, but it's good practice :) later on when you start writing your own code :).
mycubed = by_three(6)
# mycubed is now 216
mycubed2 = by_three(4)
# mycubed2 is now False.
Always return a value from a function when there is an if/elif/else
statement. But it's always, always handy to return something, no matter the situation. (note how something is the opposite of no(ne)thing)
Upvotes: 1
Reputation: 42000
Why do there need to be two instances of return?
There don't have to be - you can express the function in a many ways with just a single return
statement.
There's the "only return at the end" pattern...
def by_three(n):
if n % 3 == 0:
result = cube(n)
else:
result = False
return result
...which can be combined with the "default result" pattern...
def by_three(n):
result = False
if n % 3 == 0:
result = cube(n)
return result
...and the "do everything on one line" pattern...
def by_three(n):
return False if n % 3 else cube(n)
...which is fairly readable, but the following is not...
def by_three(n):
return next(iter(map({True: lambda x: False, False: cube}[bool(n % 3)], (n,))))
...although it still passes the tests on Codecademy.
Update
...I meant that I don't understand the need for the second instance of
return
(when it's already in the first)
Well, they're two separate functions, so each needs its own return
statement if it needs to return a value.
Upvotes: 1