When I try this code in Python 2.7.3:
names = ["Paul", "Mary", "Susan"]
names.sort()
def valuate(string):
print ord('A')
return sum(ord(s) for s in string)
i = 1
for name in names:
print i, name, valuate(name)
i += 1
I expect the output:
65
1 Mary 409
65
2 Paul 402
65
3 Susan 522
But instead I get:
1 Mary 65
409
2 Paul 65
402
3 Susan 65
522
It seems the print statement outputs the i and name values before calling the function. Is that so? Why?
The surprise you’re encountering is that the
printstatement prints out each of the expressions it is given before evaluating the next one. That is, a statement likeprint A, B, Cis equivalent to:As you’d expect from separate statements, A gets written out before B or C is evaluated.
That surprise is perhaps part of the reason that Python 3 has done away with the
printstatement in favor of a builtinprintfunction which behaves more like you expect (all of its arguments are evaluated before the function runs).In Python 2, you can get the Python 3 style
printif you want using afutureimport: