What is the purpose of the return statement?

2018-12-31 03:18发布

What is the simple basic explanation of what the return statement is, how to use it in Python?

And what is the difference between it and the print statement?

12条回答
爱死公子算了
2楼-- · 2018-12-31 03:50

Just to add to @Nathan Hughes's excellent answer:

The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"

Here's an example:

>>> def make_3_characters_long(some_string):
...     if len(some_string) == 3:
...         return False
...     if str(some_string) != some_string:
...         return "Not a string!"
...     if len(some_string) < 3:
...         return ''.join(some_string,'x')[:,3]
...     return some_string[:,3]
... 
>>> threechars = make_3_characters_long('xyz')    
>>> if threechars:
...     print threechars
... else:
...     print "threechars is already 3 characters long!"
... 
threechars is already 3 characters long!

See the Code Style section of the Python Guide for more advice on this way of using return.

查看更多
牵手、夕阳
3楼-- · 2018-12-31 03:54

I think the dictionary is your best reference here

Return and Print

In short:

return gives something back or replies to the caller of the function while print produces text

查看更多
像晚风撩人
4楼-- · 2018-12-31 03:57

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.

Example:

def timestwo(x):
    return x*2
查看更多
深知你不懂我心
5楼-- · 2018-12-31 03:57

Best thing about return function is you can return a value from function but you can do same with print so whats the difference ? Basically return not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with print because its same like stdout/cout in C Programming.

Follow below code for better understanding

CODE

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)


# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

We are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following:

  1. Our function is called with two arguments: a and b.
  2. We print out what our function is doing, in this case "ADDING."
  3. Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."
  4. Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.
查看更多
大哥的爱人
6楼-- · 2018-12-31 03:59

The cases that have not been discussed above .
The return statement allows you to terminate the execution of a function before you reach the end.The flow of execution immediately returns to the caller.

In line number 9 :

def ret(n):
    if n > 9:
         temp = "two digits"
         return temp     #Line 4        
    else :
         temp = "one digit"
         return temp     #Line 8
    return     #Line 9
    print ("return statement")
ret(10)

After the conditional statement gets executed the function ret() gets terminated due to return (line 9). Thus the print("return statement") does not get executed .

 output : two digits   

This code that appears after return statement or the place the flow of control has not reached is the dead code.

Returning Values
In line number 4 and 8 the return statement is being used to return the value of temporary variable after the condition have been executed.

To bring out the difference between print and return :

 def ret(n):
     if n > 9:
         print("two digits")
         return "two digits"           
     else :
         print("one digit")
         return "one digit"    
     return       
ret(25)


output : two digits
        'two digits'
查看更多
春风洒进眼中
7楼-- · 2018-12-31 04:00

Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.

I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.

Here is the definition of a function from Wikipedia

A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..

Think about that for a second. What does it mean when you say the function has a value?

What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)

Why would you want that you ask?

What about other functions that may accept the same type of value as an input?

def square(n):
    return n * n

def add_one(n):
    return n + 1

print square(12)

# square(12) is the same as writing 144

print add_one(square(12))
print add_one(144)
#These both have the same output

There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.

Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program

It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation. In general though, you can do things like print in a function, and you can also have a return statement at the end.

Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"

Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.

查看更多
登录 后发表回答