What is the purpose of the return statement?

后端 未结 13 2544
难免孤独
难免孤独 2020-11-21 06:28

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 state

13条回答
  •  灰色年华
    2020-11-21 06: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.

提交回复
热议问题