A Byte of Python

Logical and Physical Lines

A physical line is what you see as a single line in the program whereas a logical line is what Python sees as a single line in the program or more appropriately, what Python sees as a single statement in the program. Implicitly, Python assumes that each logical line is in a separate physical line. This is what we mean by writing each step in a separate line in the program.

An example of a logical line is the statement print 'Hello World' - if this was written in a single line by itself (as seen in your editor such as DrPython), then it also corresponds to a physical line. Python encourages one step/statement per line which makes code very readable.

Let us now understand the relationship between logical and physical lines.

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

i = 5
print i

is effectively the same as

i = 5;
print i;

which can also be written as

i = 5; print i;

or even

i = 5; print i

However, writing multiple logical lines in a single physical line is considered to be bad practice. You should write a single logical line in a single physical line as far as possible.

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

i = \
5
print i

Of course, this is a trivial example but demonstrates that if we have a long logical line, we can split it into physical lines by using the backslash at the end of the line so that Python understands that the next physical line should be considered as part of the current logical line. If you think carefully, you will realize that we are using an escape sequence here as well.

Sometimes, you don't need to specify the backslash to indicate a logical line that spans multiple physical lines. This usually happens when the logical lines uses parentheses, square brackets or curly brackets. This is called implicit line joining. We will come across examples of this later.