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

后端 未结 7 1728
死守一世寂寞
死守一世寂寞 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: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)

提交回复
热议问题