...why is there a different rule for blank lines in Python between interactive prompt and when the program is run from shell
Because, the interpreter tries to execute as soon as you hit return, but it needs the blank line to know your function, loop, if statement or other indented block is finished. If writing a function, it doesn't need (in fact won't work) if you add blank lines before the last line of the function. In this case, the blank line is needed to signal the end of the function.
You can execute a script with no blank lines from the shell, for example
for i in range(3):
print i
a = 1000
print a
Would produce
$ python test.py
0
1
2
1000
But if you paste this in the interpreter, you'll get
>>> for i in range(3):
... print i
... a = 1000
File "<stdin>", line 3
a = 1000
^
SyntaxError: invalid syntax
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
If you add a blank line to signify the end of the loop
for i in range(3):
print i
a = 1000
print a
and paste it in the interpreter,
>>> for i in range(3):
... print i
...
0
1
2
>>> a = 1000
>>> print a
1000
And that blank line must be blank, even spaces (perhaps auto added by your editor) will cause the interpreter to fail.
If you want to paste a class into the interpreter, then you don't want any spaces between any lines, including between methods. This raises a conflict with PEP8, however, meaning, you can either comply with PEP8, or be interpreter compatible, but not both.
Thus, if you want to be able to copy and paste your code into the standard python interpreter, you'll need a slightly different set of rules.
- Surround top-level function and class definitions with two blank
lines.
- A blank line is required for top level module code (outside a function or class) to end an indented block, such as a for loop, try/except or if statement.
- Blank lines may not be used within a function, class or method (barring or #).
Stick to those and you'll retain the ability to paste into the interpreter. For a class, however, you won't be strictly PEP8 as a blank line is required before and after a method.