Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens when you use another function as the argument for the print() function?

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").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading