[Python] I'm getting an IndentationError (or a TabError). How do I fix it?

Discussão em 'Python' iniciado por Stack, Fevereiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Python script:

    if True:
    if False:
    print('foo')
    print('bar')


    However, when I attempt to run my script, Python raises an IndentationError:

    File "script.py", line 4
    print('bar')
    ^
    IndentationError: unindent does not match any outer indentation level


    I kept playing around with my program, and I was able to produce four errors in total:

    • IndentationError: unexpected indent
    • IndentationError: expected an indented block
    • TabError: inconsistent use of tabs and spaces in indentation
    • IndentationError: unindent does not match any outer indentation level

    What do these errors mean? What am I doing wrong? How can I fix my code?


    This is a canonical question intended to cover ordinary causes of IndentationError in the same place, because the conceptual problem — knowing how to indent and why/where — is the same.

    There are a few established questions for certain more specific cases, where the conceptual problem isn't about the indentation per se:


    It's also possible to have logically incorrect indentation that does not cause an error. One common form of this is attaching else: to a for or while loop rather than (as intended) the corresponding if:. See Else clause on Python while statement

    See How to fix Python indentation for more tools and techniques to clean up indentation to conform to standards (even if it already "works"). Keep in mind that tools cannot automatically fix errors for you; they can only help with editing, or apply cosmetic changes that don't affect the meaning.

    Continue reading...

Compartilhe esta Página