Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I don't quite understand output received from:

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

aaa

None

None

First aaa is clear. But I thought that second print(aaa) will throw an error as variable aaa is not defined...

like image 594
pitmod Avatar asked Jun 23 '18 11:06

pitmod


People also ask

What does print (*) mean in Python?

The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

What is difference between print () and print ('\ n ') in Python?

print(' ') will print a space character and a newline; while print('') (or print() ) will only print the newline. It doesn't take away anything. Thank you very much! Now I understand why the output looked the way that it did.

How do you split a print line in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you get output in Python?

The basic way to do output is the print statement. To end the printed line with a newline, add a print statement without any objects. This will print to any object that implements write(), which includes file objects.


4 Answers

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.

like image 154
Eugene Primako Avatar answered Oct 15 '22 20:10

Eugene Primako


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

like image 27
U12-Forward Avatar answered Oct 15 '22 20:10

U12-Forward


First we just split our code

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

Now you understand !! (python 3)

like image 38
Nidhin Sajeev Avatar answered Oct 15 '22 22:10

Nidhin Sajeev


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

like image 36
Anurag Awasthi Avatar answered Oct 15 '22 22:10

Anurag Awasthi