开发者

What is usage of the last comma in this code?

开发者 https://www.devze.com 2023-03-14 08:28 出处:网络
for x in range(1, 11): print repr(x).rjust(2), repr(x*x).rjust(3), # Note trailing comma on previous line
for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3),
     # Note trailing comma on previous line
     print repr(x*x*x).rjust(4)

result:

 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

If it is a line continuation symbol, why can the author write Print state开发者_Python百科ment again?

If I remove the Print:

for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3),
     # Note trailing comma on previous line
     repr(x*x*x).rjust(4)

result:

 1   1  2   4  3   9  4  16  5  25  6  36  7  49  8  64  9  81 10 100

Obviously the last line is ignore. Why? Is it because it is not a statement?

If I put the last expression back to the second line:

for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4)

result:

 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000


It stops print from printing a newline at the end of the text.

As Dave pointed out, the documentation in python 2.x says: …. "A '\n' character is written at the end, unless the print statement ends with a comma."

UPDATE:

The documentation of python 3.x states that print() is a function that accepts the keyword argument end which defaults to a newline, \n.


A comma at the end of a print statement prevents a newline character from being appended to the string. (See http://docs.python.org/reference/simple_stmts.html#the-print-statement)

In your tweaked code:

for x in range(1, 11):
    print repr(x).rjust(2), repr(x*x).rjust(3),
    # Note trailing comma on previous line
    repr(x*x*x).rjust(4)

the last line simply becomes an unused expression because Python statements are generally separated by line breaks. If you added a backslash (\) -- the Python line continuation character -- to the end of the line of the print statement and removed the comment, then the repr(x*x*x).rjust(4) would be appended to the print statement.

To be more explicit:

print repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4)

and

print repr(x).rjust(2), repr(x*x).rjust(3), \
repr(x*x*x).rjust(4)

are equivalent, but

print repr(x).rjust(2), repr(x*x).rjust(3),
repr(x*x*x).rjust(4)

is not. This oddness of the print statement is one of the things they fixed in Python 3, by making it a function. (See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function)

0

精彩评论

暂无评论...
验证码 换一张
取 消