What is the purpose of the return statement?

后端 未结 13 2512
难免孤独
难免孤独 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:56

    return means, "output this value from this function".

    print means, "send this value to (generally) stdout"

    In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).

    This is an example of print:

    >>> n = "foo\nbar" #just assigning a variable. No output
    >>> n #the value is output, but it is in a "raw form"
    'foo\nbar'
    >>> print n #the \n is now a newline
    foo
    bar
    >>>
    

    This is an example of return:

    >>> def getN():
    ...    return "foo\nbar"
    ...
    >>> getN() #When this isn't assigned to something, it is just output
    'foo\nbar'
    >>> n = getN() # assigning a variable to the return value. No output
    >>> n #the value is output, but it is in a "raw form"
    'foo\nbar'
    >>> print n #the \n is now a newline
    foo
    bar
    >>>
    

提交回复
热议问题