PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

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

 September 15, 2022     function, printing, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing