Return


#1

I have question. In one task I saw on the end of code command return.

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 10! Make sure to
# include the number 10 between the parentheses.

squared(10)

I tried to start the code without this command and everything looked the same
Then why this command of return is?


#2

lets see:

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 10! Make sure to
# include the number 10 between the parentheses.

squared(10)
squared(5)

oh oh, only one output so return does clearly something different from print

return means literally that, the function returns something (hand something back to you), we can prove this by storing the returned result in a variable:

def example():
   return "Hello, world!"

x = example()
print x 

#3

Poorly I understand it. Return in your example as if is storing “hello word” in the function?


#4

we store the returned result in a variable named x, and then print x to see the output

This demonstrates nicely how return literally returns something/hands you something back


#5

Ok, now already I understand more, but I do not exclude that with the more complicated example I can have the problem. Thanks for help


#6

Did you run the code i provided? That might help, you can fiddle as much with the code as you need

Yea, examples might get more complex, but now with a basic understanding it should be better to understand more complex examples :slight_smile: I am sure you can manage more complex things by taking one step at a time


#7

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