Question about the return code within a function?

Hello, new here and a beginner with using Python. :grinning_face_with_smiling_eyes:

So my code looked like this:

def cube(num):

So this doesn’t work. So then I was instructed to do this (add return):

def cube(num):
   return num*num*num 

So I have two questions:

  1. Why didn’t the code work previously? Why did I have to add return?
  2. What exactly does return do? When is it useful irl?

If someone only knows the answer to 1., that’s fine too. Thanks in advance!

Hi Cindy, the return statement is the normal way to get a result from a function. If there is no return statement executed by your call of the cube function then it returns the default - None.

Your original print would have printed None, yes?

There are some languages with functions that return the result of executing their last statement if no explicit return is executed. Python is not one of those languages.

Functions can perform operations, and they can also return values.
In your first example the cube function multiplied num by itself and
then by itself again, but it wasn’t instructed to do anything with
the result. In your second example, the cube returns the result of
multiplying num by itself and by itself again, so that the value can
be used by the caller.

Technically, function calls always return something: if no explicit
return statement is reached then the function implicitly returns the
special None object on completion, so your first example was
actually printing None.

Thank you, that makes more sense. :grinning_face_with_smiling_eyes:

Thank you, I’m starting to get the hang of it. :blush: