Why does returning in Interactive Python print to sys.stdout?

后端 未结 5 1460
挽巷
挽巷 2021-01-16 04:18

I ran into something different today. Consider this simple function:

def hi():
    return \'hi\'

If I call it in a Python shell,

         


        
5条回答
  •  不知归路
    2021-01-16 04:49

    The interactive interpreter will print whatever is returned by the expression you type and execute, as a way to make testing and debugging convenient.

    >>> 5
    5
    >>> 42
    42
    >>> 'hello'
    'hello'
    >>> (lambda : 'hello')()
    'hello'
    >>> def f():
    ...     print 'this is printed'
    ...     return 'this is returned, and printed by the interpreter'
    ...
    >>> f()
    this is printed
    'this is returned, and printed by the interpreter'
    >>> None
    >>>
    

    See Read–eval–print loop on Wikipedia for more information about this.

提交回复
热议问题