Search code examples
pythonprintingreturn

Printing out function containing print and return


I recently came across a weird problem. I assumed that the two code snippets below should have the same output, yet they do not. Can someone explain?

def my_function():
    myvar = "a"
    print("2", myvar)
    return myvar
print("1")
print(my_function())

#will output:
#1
#2 a
#a
print("1", my_function())

#will output:
#2 a
#1 a

I assumed that in the second example the "1" should be printed before the function is invoked and their internal print statement is run.


Solution

  • When you call a function with parameters, the parameters have to be fully evaluated before calling the function.

    In the case of 2. python effectively rewrites your code like this:

    _ = my_function()
    print("1", _)
    

    So my_function() is called first, then the parameters are passed to print()