A Byte of Python

Logical and Physical Lines

A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.

An example of a logical line is a statement like print 'Hello World' - if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line.

Implicitly, Python encourages the use of a single statement per line which makes code more readable.

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

		
i = 5
print i
		
		

is effectively same as

		
i = 5;
print i;
		
		

and the same can 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 for a single logical line only if the logical line is really long. The idea is to avoid the semicolon as far as possible since it leads to more readable code. In fact, I have never used or even seen a semicolon in a Python program.

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 the same as

		
print i
		
		

Sometimes, there is an implicit assumption where you don't need to use a backslash. This is the case where the logical line uses parentheses, square brackets or curly braces. This is is called implicit line joining. You can see this in action when we write programs using lists in later chapters.