Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic python indentation/dedentation question

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?

like image 923
tsh Avatar asked Dec 27 '22 19:12

tsh


2 Answers

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
>>> 
like image 114
badzil Avatar answered Dec 30 '22 10:12

badzil


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
like image 45
manji Avatar answered Dec 30 '22 09:12

manji