python - I'm getting an IndentationError. How do I fix it? -
i have python script:
if true: if false: print('foo') print('bar')
however, when attempt run script, python raises indentationerror
:
file "script.py", line 4 print('bar') ^ indentationerror: unindent not match outer indentation level
i kept playing around program, , able produce 3 other errors:
- "indentationerror: unexpected indent"
- "indentationerror: expected indented block"
- "taberror: inconsistent use of tabs , spaces in indentation"
what these errors mean? doing wrong? how can fix code?
why indentation matter?
in python, indentation used delimit blocks of code. different many other languages use curly braces {}
delimit blocks such java, javascript, , c. because of this, python users must pay close attention when , how indent code because whitespace matters.
when python encounters problem indentation of program, either raises exception called indentationerror
or taberror
.
a little history
the historical reasons why python uses indentation vs arguably more commonly accepted curly braces {}
outlined in an article of history of python guido van rossum - creator of python:
python’s use of indentation comes directly abc, idea didn’t originate abc--it had been promoted donald knuth , well-known concept of programming style. (the occam programming language used it.) however, abc’s authors did invent use of colon separates lead-in clause indented block. after user testing without colon, discovered meaning of indentation unclear beginners being taught first steps of programming. addition of colon clarified significantly: colon somehow draws attention follows , ties phrases before , after in right way.
how indent code?
the basic rule indenting python code (considering treat entire program "basic block") is: first statement in basic block, , each subsequent statement after must indented same amount.
so technically following python program correct:
def perm(l): # compute list of permutations of l if len(l) <= 1: return [l] r = [] in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) x in p: r.append(l[i:i+1] + x) return r
however, can tell above, randomly indenting code makes extremely hard read , follow flow of program. it's better consistent , follow style.
pep8 - python style guide - recommends 4 spaces per indentation level should used:
use 4 spaces per indentation level.
that is, each statement starting new block , each subsequent statement in new block, should indented 4 spaces current indentation level. here above program indented according pep8 style guide:
def perm(l): # compute list of permutations of l if len(l) <= 1: return [l] r = [] in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) x in p: r.append(l[i:i+1] + x) return r
can still use tabs?
python realizes people still prefer tabs on spaces , legacy code may use tabs rather spaces, allows use of tabs indentation. pep8 touches on topic:
spaces preferred indentation method.
tabs should used solely remain consistent code indented tabs.
note 1 big caveat not use both tabs and spaces indentation. doing can cause kinds of strange hard debug indentation errors. python 3 compiler explicitly rejects program containing ambiguous mixture of tabs , spaces, raising taberror
. however, default, mixing tabs , spaces still allowed in python 2, highly recommended not use "feature". use -t
, -tt
command line flags force python 2 raise warning or (preferably) error respectively. pep8 discusses topic:
python 3 disallows mixing use of tabs , spaces indentation.
python 2 code indented mixture of tabs , spaces should converted using spaces exclusively.
when invoking python 2 command line interpreter -t option, issues warnings code illegally mixes tabs , spaces. when using -tt these warnings become errors. these options highly recommended!
what "indentationerror: unexpected indent" mean?
problem
this error occurs when statement unnecessarily indented or indentation not match indentation of former statements in same block. example, first statement in program below unnecessarily indented:
>>> print('hello') # indented file "<stdin>", line 1 print('hello') # indented ^ indentationerror: unexpected indent
in example, can_drive = true
line in if
block not match indentation of former statement:
>>> age = 10 >>> can_drive = none >>> >>> if age >= 18: ... print('you can drive') ... can_drive = true # incorrectly indented file "<stdin>", line 3 can_drive = true # incorrectly indented ^ indentationerror: unexpected indent
fix
the fix error first make sure problematic line needs indented. example, above example using print
can fixed unindenting line:
>>> print('hello') # unindent line hello
however, if sure line need indented, indentation needs match of former statement in same block. in second example above using if
, can fix error making sure line can_drive = true
indented @ same level former statements in if
body:
>>> age = 10 >>> can_drive = none >>> >>> if age >= 18: ... print('you can drive') ... can_drive = true # indent line @ same level. ...
what "indentationerror: expected indented block" mean?
problem
this error occurs when python sees 'header' compound statement, such if <condition>:
or while <condition>:
compound statement's body or block never defined. example in code below began if
statement, never define body statement:
>>> if true: ... file "<stdin>", line 2 ^ indentationerror: expected indented block
in second example, began writing for
loop, forget indent for
loop body. python still expects indented block for
loop body:
>>> names = ['sarah', 'lucy', 'michael'] >>> name in names: ... print(name) file "<stdin>", line 2 print(name) ^ indentationerror: expected indented block
comments don't count bodies:
>>> if true: ... # todo ... file "<stdin>", line 3 ^ indentationerror: expected indented block
fix
the fix error include body compound statement.
as shown above, common mistake new users forget indent body. if case, make sure each statement meant included in compound statement's body indented @ same level under compound statement's beginning. here above example fixed:
>>> names = ['sarah', 'lucy', 'michael'] >>> name in names: ... print(name) # loop body correctly indented. ... sarah lucy michael
another common case that, reason, user may not want define actual body compound statement, or body may commented out. in case, pass
statement can used. pass
statement can used anywhere python expects 1 or more statements placeholder. from documentation pass
:
pass null operation — when executed, nothing happens. useful placeholder when statement required syntactically, no code needs executed, example:
def f(arg): pass # function nothing (yet) class c: pass # class no methods (yet)
here above example if
statement fixed using pass
keyword:
>>> if true: ... pass # don't want define body. ... >>>
what "indentationerror: unindent not match outer indentation level" mean?
problem
this error occurs when unindent statement, indentation level of statement not match of former statement. example, in below code unindent second call print
. however, indentation level not match of former statement:
>>> if true: ... if true: ... print('yes') ... print() file "<stdin>", line 4 print() ^ indentationerror: unindent not match outer indentation level
this error hard catch because 1 space cause code fail.
fix
the fix ensure when unindent statement, indentation level matches of former statement. consider above example once again. in example, want second call print in first if
statements body. need make sure that line's indentation level matches of former statements in first if
statement's body:
>>> if true: ... if true: ... print('yes') ... print() # indentation level matches former statement's level. ... yes >>>
i'm still getting indentationerror program appears correctly indented. do?
if program visually appears have correct indentation, still getting indentationerror
have mixed tabs spaces. cause python raises strange errors. see subsection special cases under what "taberror: inconsistent use of tabs , spaces in indentation" mean? more in-depth explanation of problem.
what "taberror: inconsistent use of tabs , spaces in indentation" mean?
problem
this error occurs when attempt mix tabs , spaces indentation characters. said above, python not allow program contain mix of tabs , spaces, , raise specific exception taberror
if finds have. example, in program below, mix of tabs , spaces used indentation:
>>> if true: ... if true: ... print() ... print() ... print() file "<stdin>", line 5 print() ^ taberror: inconsistent use of tabs , spaces in indentation
here picture visually shows whitespace in above program. gray dots spaces, , gray arrows tabs:
we can see have indeed mixed spaces , tabs indentation.
special cases
note python will not always raise taberror
if mix tabs , spaces program. if program indentation unambiguous, python allow tabs , spaces mixed. example:
>>> if true: ... if true: # tab ... pass # tab, 4 spaces ... >>>
and python chokes on mixture of tabs , spaces , erroneously raises indentationerror
exception when taberror
more appropriate. example:
>>> if true: ... pass # tab ... pass # 4 spaces file "<stdin>", line 3 pass # 4 spaces ^ indentationerror: unindent not match outer indentation level
as can see, running code way can create mysterious errors. though program visually appears fine, python became confused trying parse tabs , spaces used indention , errored out.
these excellent examples demonstrate why never mix tabs , spaces , make use of -t
, -tt
interpreter flags when using python 2.
fix
if program short, easiest , quickest fix re-indent program. make sure each statement indented 4 spaces per indention level (see how indent code?).
however, if have large program you've mixed tabs , spaces into, there automated tools can used convert of indentation spaces.
many editors such pycharm , sublimetext have options automatically convert tabs spaces. there several on-line tools such tabs spaces or browserling allow re-indent code. there tools written in python. autopep8 example can automatically re-indent code , other indentation errors well.
even best tools though not able fix of indentation errors , you'll have fix them manually. that's why it's important indent code start.
i'm still having hard time python's indentation syntax. do?
don't discouraged if you're still struggling. can take time use python's whitespace syntax rules. here tips help:
- get editor tell when have indentation error. goods ones said above are, pycharm, sublimetext, , jupyter notebook.
- when indent code, count out loud how many times press space-bar (or tab key). example, if needed indent line 4 spaces, out loud "one, two, three, four" while simultaneously pressing space-bar each time. sounds silly, helps train brain think how deep you're indenting code.
- if have editor, see if has option automatically convert tabs spaces.
- view others' code. browse github or stackoverflow , see examples of python code.
- just write code. that's single best way better. more write python code, better you'll get.
Comments
Post a Comment