Very stupid beginner question - please help. Does print actually call the function?

From what I understand, using print on a function does not call the function, it only prints what the function returns. However, if I try the below code, it also seems to also call the function (as 5 is printed in the output),

I was just expecting it to output 5, but it seems that print has also called the function? Is this always the case? Can someone please explain!! Thank you!


def test():
x = 5


Hi there and welcome to the forums!

The reason the function is being called isn’t a result of print “calling” the function, it’s because you are using the call syntax with test(). The print function will only print out whatever it is given, and essentially what it’s being given is the function call. Therefore the function is called, a local variable x is set to 5 which is then printed and the function returns nothing. Then the print function executes, printing the value returned which as we said, is nothing, or specifically in Python None. We can see the difference in the below codebyte between the printing.

def test(): x = 5 print(f"This is inside the test function: {x}") def test2(): x = 5 print(f"This is inside the test2 function: {x}") return x print(f"This is outside the test function: {test()}") print(f"This is outside the test2 function: {test2()}")

We can see here how for test(), the function is called and the interior print statement is called first, printing our message. Then it executes the exterior print and since nothing is returned from test() it prints None. However for test2() the interior print is the same, but in the exterior print it also prints 5, since we are now returning x from the test2() function.

Hopefully that clears it up a bit, feel free to ask any questions!


Hey thanks for the help, i’ dont completely understand sorry. So are you saying that test is actually called by having test() in that print statement? And it’s not necessarily print “calling” it, it’s just test() being called because it is written there, so basically its just like a nested function? And is that why the function runs before the print statement despite it not being first if read from left to right? Thanks again!!

That’s correct yes, a function will be called anywhere that the function(<arguments>) syntax is used. In this example test takes no arguments so anywhere that test() is written the function will be called and executed before continuing with the code.

In addition, nested functions are always called inside to outside because if you’re passing a function call to another function, it’s assumed that’s because you want the result of the inner function to be passed to the outer function. Therefore test() is executed first, and then print() is executed using the value returned from test().