What’s the differences between these two pieces of code ?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 7 09:21:41 CEST 2012


On Fri, 06 Jul 2012 21:56:35 -0700, iMath wrote:

> What’s the differences between these two  pieces of code ? 

Have you tried it? What do you see?

Obviously the difference is that the second piece calls print() at the 
end, and the first does not.

Since the for-loops are identical, we can ignore them. The difference 
between the two pieces of code is the same as between

(1) (do nothing at all)

and

(2) call print()

which should be obvious: doing nothing does nothing. Calling print() 
prints a blank line.

More details below.


> (1)
> for i in range(1, 7):
> print(2 * i, end='   ')
> 
> 
> (2)
> for i in range(1, 7):
>     print(2 * i, end='   ')
> print()
> 
> 
> when executed both  respectively in Python shell ,I  get  the same
> effect . Who can tell me why  ?

No you don't get the same effect. At least not with the code as given.

The first gives a SyntaxError, as the indentation is missing. If you fix 
that problem by inserting the appropriate indentation, it prints the even 
numbers from 2 to 12, ending each number with a triple space '   ' 
instead of a newline so they all appear on the same line. Because no 
newline gets printed, the prompt appears on the same line:

py> for i in range(1, 7):
...     print(2 * i, end='   ')
...
2   4   6   8   10   12   py>

(Notice that I use "py>" as my prompt instead of ">>>".)


The second one as given also gives a SyntaxError, due to a limitation of 
the Python interactive interpreter. (When you outdent a level, you need 
to leave a blank line. The non-interactive interpreter does not have this 
limitation.) 

Fixing that problem by inserting a blank line, you get exactly the same 
numbers printed (of course! the for loops are identical), except at the 
end, after the for-loop has finished, you also call print(), which gives 
you this output:

py> for i in range(1, 7):
...     print(2 * i, end='   ')
...
2   4   6   8   10   12   py> print()

py>

Notice the blank line printed?


-- 
Steven



More information about the Python-list mailing list