The Python, The Print and The Comma

by admin on July 23, 2009 · 0 comments

On the Modules page of the Python docs, there is this code example:

def fib(n):    # write Fibonacci series up to n

  a, b = 0, 1

  while b < n:

    print b,

    a, b = b, a+b

Being new to Python, this code snippet confused me for three reasons:

  • What’s the comma at the end of the print statement for?
  • Is the “a, b = b, a+b” line a continuation of the print line?
  • And finally, is the “a, b = b, a+b” line basically three assignments separated by commas?

I knew that when given an input parameter of 1000 the Fibonacci functions outputs:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Which basically meant that my assumptions above were all wrong.

Commas at the end of Print statements

In Python, the default behavior of Print is to add a newline character at the end of the printed text – the only time the newline is not added is if a print string ends with a comma. For example:

print "line one"
print "line two"
print "line three",
print "line four"

Outputs:

line one
line two
line three line four

One subtle thing to notice with that output is the space between “line three” and “line four”. Ending a Print with a comma adds a space.

Commas in assignments

My first reaction was to read this line “a, b = b, a+b” as meaning perform three separate assignments. Clearly this couldn’t be because the “a” variable was not being assigned in any way and the known function output wouldn’t match that behaviour. What it is actually doing is assigning the values from list “b, a+b” to list “a, b”.

Previous post:

Next post: