What to do with “Unexpected indent” in python?

2019-01-02 15:06发布

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

14条回答
余生请多指教
2楼-- · 2019-01-02 15:37

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)
查看更多
初与友歌
3楼-- · 2019-01-02 15:42

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.

查看更多
泛滥B
4楼-- · 2019-01-02 15:42

Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in Sublime Editor using ctrl+b, now it will print indented code in console. that's it

查看更多
弹指情弦暗扣
5楼-- · 2019-01-02 15:43

Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.

While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.

查看更多
浪荡孟婆
6楼-- · 2019-01-02 15:48

There is a trick that always worked for me:

If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.

It happened to me when used vim, gedit or editors like that.

Try to use only 1 editor for your code.

查看更多
旧人旧事旧时光
7楼-- · 2019-01-02 15:49

By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you'll get indentation errors.

查看更多
登录 后发表回答