>A Byte of Python

Logical and Physical Lines

Python implicitly assumes that each physical line corresponds to a logical line. A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. An example of a logical line is a statement like print 'Hello World!'. If this was on a line by itself, it also corresponds to a physical line.

If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using the semicolon (;) which indicates the end of a logical line/statement. For example,

i = 5
print i
      

is effectively equal to

i = 5;
print i;
      

The neat thing is that you don't need to put the semicolon if you write a single logical line in every physical line. Experienced programmers need to remember this in particular.

The above two Python statements can also be written as

i = 5; print i;
      

or even

i = 5; print i
      

However, I strongly recommend that you stick to writing a single logical line in a single physical line only. Use more than one physical line only if the logical line is really long. Avoid using the semicolon as far as possible. In fact, I have never used or even seen a semicolon in a Python program and this makes the programs simpler and more readable.

An example of writing a logical line spanning many physical lines follows. This is referred to as explicit line joining.

s = 'This is a string. \
This continues the string.'
print s
      

This gives the output

This is a string. This continues the string.
      

Similarly,

print \
i
      

is equivalent to

print i
      

Sometimes, there is an implicit assumption in certain logical statements spanning multiple physical lines where you don't need to use the backslashes. These are statements which involve parentheses, square brackets or curly braces. This is called implicit line joining. You can see this when we write programs using lists in later chapters.