Reputation: 2395
Why does the following code produce indentation error in the Python console (version 2.6.5 in my case)? I was convinced the following was a valid piece of code:
if True:
print '1'
print 'indentation error on this line'
If I insert a blank line between the if-block and the last print, the error goes away:
if True:
print '1'
print 'no error here'
I am little bit puzzled, from the documentation it seems to me that blank (or only-white-space) lines should not make any difference. Any hints?
Upvotes: 4
Views: 1080
Reputation: 47968
The console accepts a single instruction (multiple lines if it's a definition of a function
; if
, for
, while
, ...) to execute at a time.
Here: 2 instructions
_______________
if True: # instruction 1 |
print '1' # _______________|
print 'indentation error on this line' # instruction 2 |
----------------
Here: 2 instructions separated by a blanck line; A blanck line is like when you hit enter => A single instruction by execution
if True:
print '1' # instruction 1
[enter]
print 'no error here' # instruction 1
Upvotes: 5
Reputation: 3610
The problem is due to the usage of the Python console, not the Python language. If you put everything in a method, it works.
Example:
>>> if True:
... print '1'
... print 'indentation error on this line'
File "<stdin>", line 3
print 'indentation error on this line'
^
SyntaxError: invalid syntax
>>> def test():
... if True:
... print '1'
... print 'no indentation error on this line'
...
>>> test()
1
no indentation error on this line
>>>
Upvotes: 5