How is returning the output of a function different from printing it?

后端 未结 7 1715
死守一世寂寞
死守一世寂寞 2020-11-21 11:23

In my previous question, Andrew Jaffe writes:

In addition to all of the other hints and tips, I think you\'re missing something crucial: your functio

相关标签:
7条回答
  • 2020-11-21 12:03

    Major difference:

    Calling print will immediately make your program write out text for you to see. Use print when you want to show a value to a human.

    return is a keyword. When a return statement is reached, Python will stop the execution of the current function, sending a value out to where the function was called. Use return when you want to send a value from one point in your code to another.

    Using return changes the flow of the program. Using print does not.

    0 讨论(0)
  • 2020-11-21 12:09

    A function is, at a basic level, a block of code that can executed, not when written, but when called. So let's say I have the following piece of code, which is a simple multiplication function:

    def multiply(x,y):
        return x * y
    

    So if I called the function with multiply(2,3), it would return the value 6. If I modified the function so it looks like this:

    def multiply(x,y):
        print(x*y)
        return x*y
    

    ...then the output is as you would expect, the number 6 printed. However, the difference between these two statements is that print merely shows something on the console, but return "gives something back" to whatever called it, which is often a variable. The variable is then assigned the value of the return statement in the function that it called. Here is an example in the python shell:

    >>> def multiply(x,y):
            return x*y
    
    >>> multiply(2,3) #no variable assignment
    6
    >>> answer = multiply(2,3) #answer = whatever the function returns
    >>> answer
    6
    

    So now the function has returned the result of calling the function to the place where it was called from, which is a variable called 'answer' in this case.

    This does much more than simply printing the result, because you can then access it again. Here is an example of the function using return statements:

    >>> x = int(input("Enter a number: "))
    Enter a number: 5
    >>> y = int(input("Enter another number: "))
    Enter another number: 6
    >>> answer = multiply(x,y)
    >>> print("Your answer is {}".format(answer)
    Your answer is 30
    

    So it basically stores the result of calling a function in a variable.

    0 讨论(0)
  • 2020-11-21 12:10

    The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable once the function is finished.

    >>> def foo():
    ...     print "Hello, world!"
    ... 
    >>> a = foo()
    Hello, world!
    >>> a
    >>> def foo():
    ...     return "Hello, world!"
    ... 
    >>> a = foo()
    >>> a
    'Hello, world!'
    

    Or in the context of returning a dictionary:

    >>> def foo():
    ...     print {'a' : 1, 'b' : 2}
    ... 
    >>> a = foo()
    {'a': 1, 'b': 2}
    >>> a
    >>> def foo():
    ...     return {'a' : 1, 'b' : 2}
    ... 
    >>> a = foo()
    >>> a
    {'a': 1, 'b': 2}
    

    (The statements where nothing is printed out after a line is executed means the last statement returned None)

    0 讨论(0)
  • 2020-11-21 12:11

    Print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:

    def autoparts():
      parts_dict = {}
      list_of_parts = open('list_of_parts.txt', 'r')
      for line in list_of_parts:
            k, v = line.split()
            parts_dict[k] = v
      return parts_dict
    

    Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:

    my_auto_parts = autoparts() 
    print(my_auto_parts['engine']) 
    

    See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.

    For a good tutorial, check out dive into python. It's free and very easy to follow.

    0 讨论(0)
  • 2020-11-21 12:19

    you just add a return statement...

    def autoparts():
      parts_dict={}
      list_of_parts = open('list_of_parts.txt', 'r')
      for line in list_of_parts:
            k, v = line.split()
            parts_dict[k] = v
      return parts_dict
    

    printing out only prints out to the standard output (screen) of the application. You can also return multiple things by separating them with commas:

    return parts_dict, list_of_parts
    

    to use it:

    test_dict = {}
    test_dict = autoparts()
    
    0 讨论(0)
  • 2020-11-21 12:20
    def add(x, y):
        return x+y
    

    That way it can then become a variable.

    sum = add(3, 5)
    
    print(sum)
    

    But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.

    0 讨论(0)
提交回复
热议问题