Python output from print(print(print('aaa')))

前端 未结 5 630
梦如初夏
梦如初夏 2020-12-20 18:16

I don\'t quite understand output received from:

print(print(print(\'aaa\')))

aaa

None

None

F

相关标签:
5条回答
  • 2020-12-20 18:36

    print(print('aaa'))

    The outer print will receive as argument not what inner print printed to stdout, but what inner print returned. And print function never returns anything (equivalent to returning None). That's why you see this output.

    0 讨论(0)
  • 2020-12-20 18:53

    In python, when a function returns nothing explicitly, it returns None.

    A function like print does an action but is not supposed to return anything, so it returns None. The print function could be something like this:

    import sys
    
    
    def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False)
        for arg in args:
            file.write(str(arg))
            if arg is not args[-1]:
                file.write(str(sep))
        file.write(str(end))
        if flush:
            sys.stdout.flush()
    

    Which is equivalent to:

    def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
        # The same code
        return None
    

    And in both cases you will get

    >>> print('Hello world')
    Hello world
    >>> print(print('Hello world'))
    Hello world
    None
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-20 18:55

    Here is an example which does the same thing, and you will understand it better:

    def f():
        print('Hello')
    print(f())
    

    Outputs:

    Hello
    None
    

    None is at the end because you are basically doing print(print('Hello')), print writes something in the python interpreter and also when you do type(print()) it outputs: <class 'NoneType'> So this part is print(None).

    So that's why the output of print(print(print('aaa'))) includes None's

    0 讨论(0)
  • 2020-12-20 18:56

    First we just split our code

    >>>a = print('aaa')
    aaa
    >>>b = print(a)
    None
    >>>print(b)
    None
    

    Now you understand !! (python 3)

    0 讨论(0)
  • 2020-12-20 19:01

    print prints on the standard output and returns None. Your second print statement gets result of first print which is None

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