IndentationError: unindent does not match any outer indentation level in Python

Dung Do Tien Aug 22 2021 176

Hello Guys. I created a project with Python 3.8.2 and I have a method to help get the value of an item in an array by index param input. Like:

def ColorDefined(index):
    colList = ["RED", "BLUE", "YELLOW", "BLACK"];
    if(index >=0 and index < len(colList)):
        return colList[index];
    else:
        return "Error: Index out of range";

print(ColorDefined(1));

I'm not really sure about my method but when I run it I get an error IndentationError: unindent does not match any outer indentation level.

File "main.py", line 3
    if(index >=0 and index < len(colList)):
                                          ^
IndentationError: unindent does not match any outer indentation level

I still don't understand why I got this error?

Anybody can explain to me why? And how to resolve it?

Thanks for any suggestions.

Have 3 answer(s) found.
  • Q

    Quyền Thọ Kim Quang Aug 22 2021

    I feel you do not really understand the format in Python. 

    Indent in Python throw because you are using SPACE to format code instate of using TAB to help format.

    I checked your code I see you used Space.  Please change it to Tab. See below:

    def ColorDefined(index): 
        colList = ["RED", "BLUE", "YELLOW", "BLACK"]
        if index >=0 and index < len(colList):
            return colList[index];
        else:
            return "Error: Index out of range"
    
    print(ColorDefined(1))
    #output
    BLUE

    Hope it solve for you.

  • A

    Akhmir Rudmakh Aug 22 2021

    If you are using Sublime Text users:

    Set Sublime Text to use tabs for indentation: View --> Indentation --> Convert Indentation to Tabs

    Uncheck the Indent Using Spaces option as well in the same sub-menu above. This will immediately resolve this issue.

  • N

    Nguyễn Hồng Quân Aug 22 2021

    If you are using Atom IDE

    Go to

    Packages > Whitespace > Convert Spaces to Tabs

    Then check again your file indentation:

    python -m tabnanny yourFile.py

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close