Issue
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 :)
Solution
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
.
Answered By - timgeb Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.