first = "In function first"
doesn't make the function return "In function first"
.
I can understand why you might think otherwise. In some languages, the way to return a value is to assign it to the function. In other languages, assignment is an expression, and the last expression evaluated inside a function is the return value. So, there are a lot of languages where what you're doing would work.
But Python isn't one of them. In Python, the only way to return a value is with the return
statement. And if you don't use a return
statement, the caller just gets None
.
So, your code just creates a local variable with (confusingly) the same name as the function, assigns a value to that, and then ignores that variable, so it ultimately has no effect.
What you want is:
def first():
return "In function first"
def second():
return "In function section"
print first(), second()
However, while that will give you the desired output, it isn't actually doing what you said you wanted:
Function first() should print the string "In function first()"
In that case, it should have a print
in it, not return
a value that someone else has to print.
… and then call function second().
Then you need to put the call to second()
inside the definition of first
, not outside of it.
Function second() should print the string "In function second().
And again, it should print
, not return
.
So, this is a much better match to what you were trying to do:
def first():
print "In function first"
second()
def second():
print "In function second"
first()
That being said, the code you wrote (with this fix) actually seems like better code than the code you wanted to write. Returning values from inner functions and handling output at the highest level is generally more flexible than having print
s all over the place.