Queries regarding print() function

Question:

print("Line 1")
print(">>>")
type(print("Hello"))
print()

print("Line 2")
print(">>>")
print(print("Hello"))
print()

print("Line 3")
print(">>>")
a = print("Hello")
b = a
print("a:", a, "b:", b)

Q1) For Line 1, why is it that type(None) not be executed since print("Hello") returns None ?

Q2) I am sort of aware that IIFE is a term usually associated with JavaScript but I am wondering why Python’s print() function seems to display certain IIFE properties like running a function the moment it is invoked (as seen in the output for Line 3) ?


Below is the output for the code above (for Python 3.9):

Line 1
>>>
Hello

Line 2
>>>
Hello
None

Line 3
>>>
Hello
a: None b: None
Asked By: rustlecho

||

Answers:

An IIFE is an expression that creates an anonymous function and immediately calls it. Due to how function declarations in Python work, the concept is not really available here. You can only use this for lambda expressions which only have a very limited use case for IIFEs:

>>> (lambda x: x + 2)(2)
4

I am not entirely sure what you think that you see in your Python example. However, print() is a function that, when called, will print out its argument and return None.

So when you do something like print(print("Hello")), then the evaluation works from inside to the outside:

  1. "Hello" is created as a string.
  2. print("Hello") runs, prints out the string and returns the value None
  3. print(print("Hello")) runs, which does print(None) since the inner function call resolves to None (after that inner call is executed)

With that same reasoning you can explain the other examples, e.g. the following:

a = print("Hello")
# -> "Hello" is printed, the function returns `None`
# -> `a = None`
b = a
# -> so `b = None` since a equals `None`
print("a:", a, "b:", b)
# -> a and b are both `None` so this is equal to:
#    print("a:", None, "b:", None)
#    which explains the output
Answered By: poke