Issue
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?
Solution
The surprise you're encountering is that the print
statement prints out each of the expressions it is given before evaluating the next one. That is, a statement like print A, B, C
is equivalent to:
print A, # note, the trailing comma suppresses the newline
print B,
print C
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 print
statement in favor of a builtin print
function 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 print
if you want using a future
import:
from __future__ import print_function
Answered By - Blckknght
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.