3. Call and Response - What is the purpose of the return statement in this function?


#1



https://www.codecademy.com/en/courses/python-beginner-c7VZg/1/2?curriculum_id=4f89dab3d788890003000096


I am struggling to understand what the purpose is of the return statement in the function below. The print statement can be printed to the console without the return statement. Thus, it seems that, in this function, the return statement serves no purpose. What is the purpose of the return statement here? Have I overlooked something about the return operator?


def square(n):
    """Returns the square of a number."""
    squared = n**2
    print "%d squared is %d." % (n, squared)
    return squared
# Call the square function on line 9! Make sure to
# include the number 10 between the parentheses.
square(10)


#2

A function call is asynchronous, meaning two-way communication. The function sees what the caller sends it, in it's solved form, and the caller sees the return value.


#3

Ah, I see. Thanks for explanation. :slight_smile:


#4

I should add though that there are two scopes involved. That of the caller, and that of the callee. In Python the indentation indicates to the interpreter a change in block scope which is slightly different than environment that scope implies (def function():). In a single environment, block scope variables are all visible to each other.

We use the formal parameter to receive data from the caller, known as arguments. The function can then process that data using the names of the objects given in the parameter list to reference their values. Parameters are local variables in an entirely alien scope to the caller.

The return statement is the vehicle by which data goes back to the caller's scope where it is likely assigned to a variable in that scope.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.