What is a "Return" used for and why do I need it?


#1



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

I'm not really stuck on this lesson, I just don't quite understand what a return is. I can't figure out what it does because even after commenting it out, the code still does the same thing.

If someone could explain, in simple terms, what a return is and how to use it, that would help me a lot. Thanks!


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

Hello @theeubermedic,

Inside of a function, what the return statement does is that is specifies what value it should output. Like for instance the len() function returns the length of the string or iterable passed inside it. In the same way, your square() function returns squared, which is the value of n squared...


#3

How is that different from printing it?


#4

By returning it you don't print it on the console. But, when printing it, it prints onto the console


#5

So when you return something, where is it stored, and how can I access it?

For example:

def cube(number):
return number**3

def by_three(number):
if number % 3 == 0:
return cube(number)

else:
    return False

by_three(3)

This returns 27, so how do I access that 27?


#6

So I figured I could just do this.

result = by_three(3) #then if I need to access it, I can just print result.