user8784327
user8784327

Reputation:

Why is this piece of code printing out hi?

z = print('hi')

I understand print functions returns literally nothing . So when I type print(z) I get None value. My question is why does the piece of code below print hi

>>> z = print('hi')
hi
>>> print(z) 
None 

Why is this not happening

>>>x = max('Hello world')
w

Upvotes: 0

Views: 106

Answers (1)

paxdiablo
paxdiablo

Reputation: 882226

I understand print functions returns literally nothing.

Yes but, apparently, you don't understand that it first prints out what you give it and then returns nothing :-) That is what it's meant to do.

The max, in exactly the same way, does what it is specified to do, which is return the maximum item after not printing anything. The printing of w that you're seeing has nothing to do with what max is doing, it's because the Python REPL loop(a) will print out the result of any statement that isn't None:

>>> None
>>> 1
1
>>> "hello"
'hello'
>>> False
False
>>> True
True
>>> 0
0
>>> def retNone(): return None
... 
>>> def retOne(): return 1
... 
>>> retNone()
>>> retOne()
1

If you want z to be given the thing you're currently printing, you can just use:

z = 'hi'

or, for more complex cases, Python has formatting options for you, such:

showPi = "Pi is roughly {}".format(355/113)

Neither of those will print the string you're creating until you explicitly want to, or unless you're in the REPL loop.


(a) Yes, I know what the L stands for, I'm just following the time-honoured traditions of "ATM machine", "HIV virus" and "LCD display" as per the requirements of the "RAS syndrome" :-)

Upvotes: 6

Related Questions