What to do with “Unexpected indent” in python?

前端 未结 17 2387
天涯浪人
天涯浪人 2020-11-22 07:46

How do I rectify the error \"unexpected indent\" in python?

相关标签:
17条回答
  • 2020-11-22 08:22

    If you're writing Python using Sublime and getting indentation errors,

    view -> indentation -> convert indentation to spaces

    The issue I'm describing is caused by the Sublime text editor. The same issue could be caused by other editors as well. Essentially, the issue has to do with Python wanting to treat indentations in terms of spaces versus various editors coding the indentations in terms of tabs.

    0 讨论(0)
  • 2020-11-22 08:22

    One issue which doesn't seem to have been mentioned is that this error can crop up due to a problem with the code that has nothing to do with indentation.

    For example, take the following script:

    def add_one(x):
        try:
            return x + 1
    add_one(5)
    

    This returns an IndentationError: unexpected unindent when the problem is of course a missing except: statement.

    My point: check the code above where the unexpected (un)indent is reported!

    0 讨论(0)
  • 2020-11-22 08:23

    This error can also occur when pasting something into the Python interpreter (terminal/console).

    Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like

    def my_function():
        x = 3
    
        y = 7
    

    the interpreter will interpret the empty line before y = 7 as the end of the expression, i.e. that you're done defining your function, and the next line - y = 7 will have incorrect indentation because it is a new expression.

    0 讨论(0)
  • 2020-11-22 08:23

    All You need to do is remove spaces or tab spaces from the start of following codes

    from django.contrib import admin
    
    # Register your models here.
    from .models import Myapp
    admin.site.register(Myapp)
    
    0 讨论(0)
  • 2020-11-22 08:24

    Run the following command to get it solved :

    autopep8 -i <filename>.py
    

    This will update your code and solve all indentation Errors :)

    Hope this will solve

    0 讨论(0)
提交回复
热议问题