Call and Response. Why is 'return' necessary?>


#1


Just curious why this function from exercise 7.13, 'Call and Response' requires a return command. When I remove it, the code works as hoped. What's the importance of the return command that I am missing?


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

Hi,
I'm not familiar with the exercise or how 'return' applies to the exercise (I have never taken the Python course), but I know why 'return' is important, in case that's what you need to know :slight_smile:

'Return' is how you get a value out of a function.
Say, for example, you have the function 'add numbers' which adds two numbers provided.
def add(a, b):
total = a + b

This will run the code, but it doesn't provide a value. However, if you add a return command (return total) to the end, it will return 'total' as a value. This allows you to set variables to the product of a function, etc.

myVariable = add(1,2)
print myVariable

If you need me to clarify, I will be able respond within a few hours. If this is not what you are looking for, or if my answer is irrelevant to Python, I'm sorry!


#3

Hi,
@mabviro Gave a great explanation about return statements in general, but usually you need to return something for a function. Many people confuse return and print statements, so make sure you know the difference between those two.


#4

it is to kind of store variables in case the next cod calls it


#5

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