1

I'm a beginner so I don't understand much about the underlying processes behind the print() function but I'm curious about the process behind something like this:

def test():
    print("hi")
    return "hi"

print(test())

This outputs both the "hi" message from the print() within the test() function as well as the "hi" from the return statement. Instinctively, I would have expected only the "hi" from the return statement.

Can anyone explain in simple terms why we get both? I expect it's something along these lines: When using a function output such as test() as the argument for the print function, the test() function is first invoked (hence producing the first "hi") and then its return output is printed (producing the second "hi").

Am I right to any extent here? I'd be grateful for any light that can be shed on what's going on here and improve my understanding :)

Refnom95
  • 113
  • 3
  • 1
    Yes, your interpretation is correct. Every `print` produces exactly one output. It doesn't matter that it's called "inside another `print`", which it isn't really anyway. – deceze Jan 13 '22 at 11:19
  • 2
    replace ```return "hi 2"```. you ll get the idea. one ```hi``` from print statement in function and second from print statement outside which is printing the return value. – shivankgtm Jan 13 '22 at 11:19
  • 2
    "Instinctively, I would have expected only the "hi" from the return statement." Why? First of all, important to note, you *aren't using a function as the argument for `print`*, You are *calling the `test` function* and the *result* of that is passed to `print`. When you *call `test`, i.e. `test()`*, the function executes, which executes the `print("hi")` and then returns `"hi"`, this return value is passed to the `print()` which is then printed. – juanpa.arrivillaga Jan 13 '22 at 11:19

1 Answers1

1

It's quite simple

print(test())

is equivalent to

result = test()
print(result)

The first line calls the test function (which prints 'hi' in its body) and assigns the name result to the return value, which coincidally is also 'hi'.

The second line prints the value returned by test.

timgeb
  • 76,762
  • 20
  • 123
  • 145