Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is usage of the last comma in this code?

Tags:

python

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 statement 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
like image 438
lamwaiman1988 Avatar asked Jun 22 '11 02:06

lamwaiman1988


2 Answers

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.

like image 111
bradley.ayers Avatar answered Nov 20 '22 01:11

bradley.ayers


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)

like image 44
Joe Shaw Avatar answered Nov 20 '22 00:11

Joe Shaw