What to do with “Unexpected indent” in python?

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

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

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

    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.

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

    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.

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

    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

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

    If the indentation looks ok then have a look to see if your editor has a "View Whitespace" option. Enabling this should allow to find where spaces and tabs are mixed.

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

    In Python, the spacing is very important, this gives the structure of your code blocks. This error happens when you mess up your code structure, for example like this :

    def test_function() :
       if 5 > 3 :
       print "hello"
    

    You may also have a mix of tabs and spaces in your file.

    I suggest you use a python syntax aware editor like PyScripter, or Netbeans

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

    Make sure you use the option "insert spaces instead of tabs" in your editor. Then you can choose you want a tab width of, for example 4. You can find those options in gedit under edit-->preferences-->editor.

    bottom line: USE SPACES not tabs

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