-1
print("Klay", print("Thompson"))

Running this code gives an output of

Thompson
Klay None

Why does the internal print execute before the outer one? I expected the output to be

Klay Thompson
None
Kun.tito
  • 165
  • 1
  • 7
  • 2
    Python has to resolve all of the parameters you're passing to the outer `print`, including calling the inner `print`, before it can call it. – jonrsharpe Jul 06 '21 at 11:38
  • 3
    There are no print statements. `print` is a function, just like any other. When you call a function, `foo(, )` the expressions that are part of the function call arguments are evaluated in-order *before the function is called*. If those expressions *happen to be other function calls*, well, they get called first – juanpa.arrivillaga Jul 06 '21 at 11:38
  • see: https://stackoverflow.com/a/17948641/5014455 – juanpa.arrivillaga Jul 06 '21 at 11:41
  • Your puzzle is because your code prints the value of the expression `print("Thompson")` which will be `None` unless you have redefined `print`. But even though you know you have not redefined it, the interpreter will still call it to get the returned value. But calling it has the side effect of printing `Thompson`. Then, after that call returns, the outer `print` call can assemble the values of the 2 expressions into a line and send them to the console. – BoarGules Jul 06 '21 at 13:49

1 Answers1

0

When using nested print statements in python it is important to note that print will first execute all print statements nested int it first from left to right(like all functions) to get the returned value which will always be none unless redefined, and then the result is constructed from right to left. So, when print('Thompson') is run the print statement will return none and print Thompson to the shell. Then the outer print statement prints the first value and the returned value of the inner print which will be none

TERMINATOR
  • 1,180
  • 1
  • 11
  • 24