Indentationerror unexpected unindent как исправить

IndentationError: unexpected unindent WHY??? #!/usr/bin/python import sys class Seq: def __init__(self, id, adnseq, colen): self.id = id self.dna = adnseq self.c...

IndentationError: unexpected unindent WHY???

#!/usr/bin/python
import sys
class Seq:
    def __init__(self, id, adnseq, colen):
        self.id     = id
        self.dna    = adnseq
        self.cdnlen = colen
        self.prot   = ""
    def __str__(self):
        return ">%sn%sn" % (self.id, self.prot)
    def translate(self, transtable):
        self.prot = ""
        for i in range(0,len(self.dna),self.cdnlen):
            codon = self.dna[i:i+self.cdnlen]
            aa    = transtable[codon]
            self.prot += aa
    def parseCommandOptions(cmdargs):
        tfname = cmdargs[1]
        sfname = cmdargs[2]
        return (tfname, sfname)
    def readTTable(fname):
        try:
            ttable = {}
            cdnlen = -1
            tfile = open(fname, "r")
            for line in tfile:
                linearr = line.split()
                codon   = linearr[0]
                cdnlen  = len(codon)
                aa      = linearr[1]
                ttable[codon] = aa
            tfile.close()
            return (ttable, cdnlen)
    def translateSData(sfname, cdnlen, ttable):
        try: 
            sequences = []
            seqf = open(seq_fname, "r")
            line = seqf.readline()
            while line:
                if line[0] == ">":
                    id = line[1:len(line)].strip()
                    seq = ""
                    line = seqf.readline()
                    while line and line[0] != '>':
                        seq += line.strip()
                        line = seqf.readline()  
                    sequence = Seq(id, seq, cdnlen)
                    sequence.translate(ttable)
                    sequences.append(sequence)
            seqf.close()
            return sequences    
    if __name__ == "__main__":
        (trans_table_fname, seq_fname) = parseCommandOptions(sys.argv)
        (transtable, colen) = readTTable(trans_table_fname)
        seqs = translateSData(seq_fname, colen, transtable)
        for s in seqs:
            print s

It says:

 def translateSeqData(sfname, cdnlen, ttable):
   ^
IndentationError: unexpected unindent

WHY? I have checked a thousands times and I can’t find the problem. I have only used Tabs and no spaces. Plus, sometimes it asks to define the class. Is that Ok?

In this post , we will see How to Fix Various Indentation Errors in Python.

Spacing is important in Python since the coding is dependent of the place or line where a code block starts or ends. Hence Indentation is crucial in Python coding.

P.S. – Once you read this post , go through our earlier post for extra tips –How To Fix – Indentation Problem in Python ? 


if( aicp_can_see_ads() ) {

}

Let us see the various types of Indentation Errors in Python –

1. IndentationError: unexpected indent –


Consider the example below –

>>>    print "hello world"
IndentationError: unexpected indent

The reason for this is the “EXTRA SPACE” before the command “print”

Fix –


if( aicp_can_see_ads() ) {

}

  • Check if  spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
  • Remove Extra Spaces
    Better to use Spaces than Tabs.
  • For 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.
  • For  Notepad++ , Change Tab Settings to 4 spaces
    Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

2. IndendationError: Unindent does not match any outer indentation level –


This happens when Python cannot decide whether a specific statement belongs to a specific Code-Block or Not (due to Indentation – might be copy-paste code).

For instance, in the following, is the final print supposed to be part of the if clause, or not?

Example Below –


if( aicp_can_see_ads() ) {

}

>>> if acc_name == "NYC":
...   print "New York Region !"
... print "Where do I belong ?"
IndendationError: unindent does not match any outer indentation level

Fix

  • Check if  spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
  • Remove Extra Spaces
  • Better to use Spaces than Tabs.
  • For 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.
  • For  Notepad++ , Change Tab Settings to 4 spaces
    Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

3. IndentationError: expected an indented block –


Normally occurs when a code block (if/while/for statement , function block etc.) , does not have spaces.  See example below –


if( aicp_can_see_ads() ) {

}

This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).

>>> def foo():
... print "hello world"
IndentationError: expected an indented block

Fix


if( aicp_can_see_ads() ) {

}

  • Check if  spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
  • Remove Extra Spaces
    Better to use Spaces than Tabs.
  • For 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.
  • For  Notepad++ , Change Tab Settings to 4 spaces
    Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Hope this helps .

Other Interesting Reads –

  • How To Fix – “Ssl: Certificate_Verify_Failed” Error in Python ?

  • How To Make Your Laptop or Desktop A Public Server (NGROK) ?

  • How To Setup Spark Scala SBT in Eclipse

  • How To Save & Reload a Python Machine Learning Model using Pickle ?

[the_ad id=”1420″]


if( aicp_can_see_ads() ) {

}

python indentation,python indentation error, unindent does not match any outer indentation level , expected an indented block , python expected an indented block, indentationerror, indented block python, indentation, python, pycharm, django, python fix indentation,python indentation fixer,python fix,python indentation rules,python fix indentation,indented block in python,indentationerror
python indentation ,python indentation checker ,python indentation error ,python indentationerror unexpected indent ,python indentation rules ,python indentation shortcut ,python indentationerror expected an indented block ,python indentation example ,python indentation error fix ,python indentation annoying ,python indentation automatic ,python indentation and spacing ,python indentation atom ,python indentation alternative ,python indentation arguments ,python indentation after while loop ,python indentation antlr ,python indentation best practices ,python indentation block ,python indentation brackets ,python indentation blank line ,python indentation broken ,python indentation button ,python indented block error ,python indent block of code ,python indentation codeforces ,python indentation convention ,python indentation contains tabs ,python indentation command line ,python indentation code ,python indentation does not match ,python indentation definition ,python indentation docs ,python indentation delete ,python indentation disable ,python indentation docstring ,python dictionary indentation ,python default indentation ,python indentation error fix online ,python indentation error check online ,python indentation error notepad++ ,python indentation error unindent ,python indentation formatter ,python indentation fix ,python indentation for loop ,python indentation for if ,python indentation function arguments ,python indentation function ,python indentation for ,python indentation format ,python indentation guide ,python indentation grammar ,python indentation geany ,vim indent python ,python get indentation level ,python get indentation ,python group indent ,python get index of string ,python indentation how many spaces ,python indentation hell ,python indentation helper ,python indentation haskell ,python indent html ,python indent hotkey ,python hanging indentation ,python heredoc indentation ,python indentation in visual studio code ,python indentation in notepad++ ,python indentation in hindi ,python indentation in vscode ,python indentation is not a multiple of four ,python indentation if statement ,python indentation in vim ,python indentation issues ,python indentation js ,python indent json ,python indent json command line ,indentation python jupyter ,python json indent=4 ,python json indent level ,python json indent tab ,python jsonpickle indent ,python kate indentation ,python keyboard indent indented python key ,python indentation long lines ,python indentation level ,python indentation line break ,python indentation length ,python indentation line ,python indent long if statement ,python indent left ,python indent list comprehension ,python indentation meaning ,python indentation meme ,python indentation multiple lines ,python indentation matters ,python indentation multiline string ,python mixed indentation ,python method indentation ,python markdown indentation ,python indentation notepad++ ,python indentation number of spaces ,python indentation not working ,python indentation new line ,python indentation nested ,python indentation number ,python indent no ,python notepad++ indentation error ,python indentation online ,python indentation of output ,python indentation of ,python-indent-offset ,python-indent-offset spacemacs ,python outer indentation level ,python object indentation ,python over-indented ,python indentation pep8 ,python indentation problem ,python indentation print ,python indentation pycharm ,python indentation purpose ,python indent plugin notepad++ ,python indent paragraph ,python print indentation error ,python triple quotes indentation ,qgis python indentation error ,indentation python c'est quoi ,python indentation reddit ,python indentation rules pdf ,python indentation return ,python indentation recommendation ,python indentation remove ,python indentation range ,python indentation right ,python indentation spaces ,python indentation space or tab ,python indentation solver ,python indentation sublime text 3 ,python indentation syntax ,python indentation size ,python indentation syntax error ,python indentation tool ,python indentation tab or space ,python indentation tab ,python indentation tutorial ,python indentation tab vs space ,python indentation try except ,python indentation tutorialspoint ,python indentation to spaces ,python indentation using ,python indent unindent ,python indent unexpected ,python uses indentation to indicate a block of code ,python uses indentation ,python uses indentation for blocks ,python unexpected indentation error ,python url indentation ,python indentation vscode ,python indentation validator ,python indentation vim ,python indentation vs braces ,python indentation visual studio ,python indentation variable scope ,python indentation vs spaces ,python indenting vs ,python indentation w3schools ,python indentation while loop ,python indentation windows linux ,python indentation width ,python indentation with 2 spaces ,python indentation wrong ,python indentation working ,python indent whole block ,python xml indentation ,python indentation in xcode ,xcode python indentation problems ,python yaml indentation ,python your indentation is outright incorrect ,python yaml indent list ,yasnippet python indentation ,youtube python indentation ,python indentation ,python indentation check ,python check indentation in notepad++ ,python indentation check online ,python indentation checker online ,python indent checker online ,python indent check online ,python indentation corrector ,python code indentation checker ,python indentation online checker ,python indentation check tool ,python indentation error sublime ,python indentation error after for loop ,python indentation error after if ,atom python indentation error ,python avoid indentation error ,python getting an indentation error ,python expected indented block error ,blender python indentation error ,check python indentation error ,python comment indentation error ,python class indentation error ,indentation error python codecademy ,python causing indentation error ,vs code python indentation error ,python command line indentation error ,python indentation error def ,python indentation error unindent does not match ,python docstring indentation error ,python error inconsistent indentation detected ,indentation error python deutsch ,python indentationerror expected an indented block for loop ,python indentation error example ,python indentation error else ,python indent expected error ,python elif indentation error ,python except indentation error ,indentation error python eclipse ,python indentation error for loop ,python indentation error for print ,python find indentation error ,python for indentation error ,indentation error in python for if ,geany python indentation error ,python keep getting indentation error ,python indentation error handling ,python how to fix indentation error ,how to check python indentation error ,python indentation error if ,indentation error in python ,indentation error in python 3 ,indentation error in python for loop ,indentation error in python print ,python idle indentation error ,indentation error in python vscode ,indentation error in python sublime text ,what is python indentation error ,how to handle indentation error in python ,python indentation error linux ,indentation error in python if loop ,indentation error meaning python ,maya python indentation error ,python multiline comment indentation error ,python indentation error nedir ,python nested if indentation error ,python indentation error online ,indentation error on python ,indentation error in python stack overflow ,raspberry pi python indentation error ,python indentation error remove ,python return indentation error ,python indentation error solve ,python shell indentation error ,python script indentation error ,visual studio python indentation error ,python if statement indentation error ,python terminal indentation error ,python try indentation error ,sublime text python indentation error ,python indentationerror unexpected unindent ,python indentationerror unexpected indent block ,python indentation error vim ,vscode python indentation error ,visual studio code python indentation error ,python while indentation error ,
python with indentation error ,indentation error in python while loop ,meaning of indentation error in python ,python indentationerror unexpected indent notepad++ ,python indentationerror unexpected indent comment ,vscode python indentationerror unexpected indent ,python 2.7 indentationerror unexpected indent ,python try indentationerror unexpected indent ,python ast indentationerror unexpected indent ,python exec indentationerror unexpected indent ,indentationerror unexpected indent python class ,python command line indentationerror unexpected indent ,indentationerror unexpected indent python visual studio code ,python def indentationerror unexpected indent ,python indentationerror unexpected indent error ,python if else indentationerror unexpected indent ,python parsing error indentationerror unexpected indent ,erro python indentationerror unexpected indent ,python for indentationerror unexpected indent ,indentationerror unexpected indent python for loop ,indentationerror unexpected indent python function ,python open file indentationerror unexpected indent ,python + indentationerror unexpected indent ,how to fix indentationerror unexpected indent in python ,indentationerror unexpected indent python ,indentation error in python unexpected indent ,indentationerror unexpected indent python 3 ,python indentationerror unexpected indent if ,indentationerror unexpected indent python jupyter notebook ,error unexpected indent python ,linux python indentationerror unexpected indent ,python for loop indentationerror unexpected indent ,python indentationerror unexpected indent print ,indentationerror unexpected indent pada python ,python unexpected indent for loop ,python shell indentationerror unexpected indent ,python sorry indentationerror unexpected indent ,python timeit indentationerror unexpected indent ,vim python indentationerror unexpected indent ,python while indentationerror unexpected indent ,what is indentationerror unexpected indent in python ,python 3 indentation rules ,indentation rules for python ,indentation rules in python ,indentation rules in python 3 ,python rules of indentation ,python idle indentation shortcut ,python auto indent shortcut ,vscode python indent shortcut ,python indent block shortcut ,indentation shortcut in python ,python shortcut for indentation ,shortcut key for indentation in python ,shortcut for indentation in python ,python indent shortcut ,indentation python shortcut ,python indentationerror expected an indented block if ,python indentationerror expected an indented block notepad++ ,python indentationerror expected an indented block try ,python interpreter indentationerror expected an indented block ,python elif indentationerror expected an indented block ,python return indentationerror expected an indented block ,python comment indentationerror expected an indented block ,error in python indentationerror expected an indented block ,how to fix expected an indented block in python ,python function indentationerror expected an indented block ,indentationerror expected an indented block in python ,python expected an indented block ,python print indentationerror expected an indented block ,python console indentationerror expected an indented block ,python class indentationerror expected an indented block ,python command line indentationerror expected an indented block ,python csv indentationerror expected an indented block ,python def indentationerror expected an indented block ,python indentationerror expected an indented block deutsch ,python error indentationerror expected an indented block ,erreur python indentationerror expected an indented block ,que significa en python indentationerror expected an indented block ,indentationerror expected an indented block python español ,erro python indentationerror expected an indented block ,how to fix indentationerror expected an indented block in python ,python fehler indentationerror expected an indented block ,python error expected an indented block ,how to remove indentationerror expected an indented block in python ,indentationerror expected an indented block in python for loop ,indentationerror expected an indented block in python script ,indentationerror expected an indented block meaning in python ,how to solve indentationerror expected an indented block ,python while loop indentationerror expected an indented block ,python indentationerror expected an indented block main ,python indentationerror expected an indented block print ,indentationerror expected an indented block print python 3 ,raspberry pi python indentationerror expected an indented block ,indentationerror expected an indented block python shell ,python sorry indentationerror expected an indented block ,python script indentationerror expected an indented block ,python if statement indentationerror expected an indented block ,python indentation how to ,python indentation tool ,python indentation to spaces ,python indentation to ,python how to fix indentation error ,python how to check indentation ,python how to fix indentation ,python how to create indentation ,python indentation annoying ,python indentation automatic ,python indentation atom ,python indentation and spacing ,python indentation alternative ,python indentation arguments ,python indentation after while loop ,python indentation antlr ,python indentation best practice ,python indentation block ,python indentation brackets ,python indentation blank line ,python indentation broken ,python indentation button ,,python indented block error ,python indent block of code ,python indentation checker ,python indentation check ,python indentation codeforces ,python indentation convention ,python indentation contains tabs ,python indentation command line ,python indentation correction ,python indentation contains mixed spaces and tabs ,python indentation does not match ,python indentation definition ,python indentation docs ,python indentation delete ,python indentation disable ,python indentation docstring ,python indentation error def ,indentation python docx ,python indentation error ,python indentation error fix ,python indentation error check online ,python indentation example ,python indentation error unindent ,python indentation explained ,python indentation editor online ,python indentation error notepad++ ,python indentation fixer ,python indentation formatter ,python indentation fix ,python indentation for loop ,python indentation function arguments ,python indentation function ,python indentation for if else ,python indentation for ,python indentation guide ,python indentation grammar ,python indentation geany ,vim indent python ,how to give indentation in python ,python indentation hell ,python indentation helper ,python indentation haskell ,python indent html ,python indent hotkey ,python indentation in hindi ,python indentation error handling ,indentation python help ,python indentation is not a multiple of four ,python indentation in vim ,python indentation if statement ,python indentation if else ,python indentation in notepad++ ,python indentation in visual studio code ,python indentation issues ,python indentation in sublime ,python indentation js ,python indented text to json ,python indent json ,python indent json command line ,indentation python jupyter ,python indent to left ,python indentation level ,python indentation long lines ,python indentation line break ,python indentation length ,python indentation line ,python indent long if statement ,python indent list comprehension ,python indentation how many spaces ,python indentation multiple lines ,python indentation meaning ,python indentation meme ,python indentation matters ,,python indentation multiline string ,how to make indentation in python ,python indentation notepad++ ,python indentation number of spaces ,python indentation not working ,python indentation new line ,python indentation nested ,python indentation number ,python indent no ,python indentation online ,python indentation of ,python indent output ,python-indent-offset ,python-indent-offset spacemacs ,python indentation 2 or 4 spaces ,python indentation tab or space ,python indentation problem ,python indentation pep8 ,python indentation print ,python indentation pycharm ,python indentation purpose ,python indent plugin notepad++ ,python indent paragraph ,indentation python programming ,python indentation rules ,python indentation rules pdf ,python indentation reddit ,python indentation return ,python indentation recommendation ,python indentation remove ,python indentation range ,python indentation right ,python indentation shortcut ,python indentation space or tab ,python indentation sublime text 3 ,python indentation size ,python indentation syntax ,python indentation syntax error ,python indentation spaces vs tabs ,python indentation tutorial ,python indentation tab vs space ,python indentation tab ,python indentation try except ,python indentation tutorialspoint ,python indentation using ,python indent unindent ,python indent unexpected ,python indentationerror unexpected unindent ,python indentation vim ,python indentation vscode ,python indentation validation ,python indentation validation online ,python indentation vs braces ,python indentation visual studio ,python indentation variable scope ,python indentation vs spaces ,python indentation w3schools ,python indentation while loop ,python indentation windows linux ,python indentation width ,python indentation with 2 spaces ,python indentation wrong ,python indentation working ,python indent whole block ,python indentation in xcode ,python formatter tool ,python fix indentation tool ,python indentation check tool ,indentation tool for python ,python indentation ,python indentation tool online ,python indent online ,python indent spaces or tab ,python indentation 4 spaces ,python indentation 2 spaces ,python indentation four spaces ,python tabs to spaces convert ,python tabs and spaces error ,python mixed indentation spaces found ,python indentation in spaces ,python tabs to spaces online ,python indentation space tab ,python convert tabs to spaces vim ,python tabs vs spaces ,python indent with spaces ,python write indented json to file ,python add indentation to string ,python uses indentation to indicate a block of code ,how to fix indentation error in python using notepad++ ,how to fix indentation error in python online ,python correct indentation errors ,how to fix an indentation error in python ,how to fix indentation error in python ,how to handle indentation error in python ,how to correct indentation error in python ,how to fix unexpected indent error in python ,python check indentation online ,python check indentation in notepad++ ,how to check python indentation error ,python check for indentation ,python check file indentation ,how to check indentation in python ,how to check indentation error in python ,python fix indentation online ,python fix indentation notepad++ ,python fix indentation vscode ,python fix indentation sublime ,python how to fix unexpected indent ,python spyder fix indentation ,python fix all indentation ,how to fix indented block in python ,python fix indentation command line ,how to fix indentation in sublime for python ,how to fix indentation in python ,how to fix python indentation in notepad++ ,how to fix indentation in python spyder ,how to fix indentation in python pycharm ,how to correct indentation in python jupyter notebook ,python fix indentation linux ,python fix mixed indentation ,how to fix indentation problem in python ,python fix indentation script ,how to fix the indentation in python ,python fix indentation vim ,python create indented block ,how to create indentation in python ,vim python automatic indentation ,python editor automatic indentation ,spyder python automatic indentation ,python disable automatic indentation ,python automatic indentation ,


if( aicp_can_see_ads() ) {


if( aicp_can_see_ads() ) {

}

}

Программирование, Python, Учебный процесс в IT, Блог компании SkillFactory


Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

image

Выяснить, что означают сообщения об ошибках Python, может быть довольно сложно, когда вы впервые изучаете язык. Вот список распространенных ошибок, которые приводят к сообщениям об ошибках во время выполнения, которые могут привести к сбою вашей программы.

1) Пропуск “:” после оператора if, elif, else, for, while, class или def. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Пример кода с ошибкой:

if spam == 42

    print('Hello!')

2) Использование = вместо ==. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

= является оператором присваивания, а == является оператором сравнения «равно». Пример кода с ошибкой:

if spam = 42:

    print('Hello!')

3) Использование неправильного количества отступов. (Сообщение об ошибке: «IndentationError: unexpected indent» и «IndentationError: unindent does not match any outer indentation level» и «IndentationError: expected an indented block»)

Помните, что отступ увеличивается только после оператора, оканчивающегося на “:” двоеточие, и впоследствии должен вернуться к предыдущему отступу.
Пример кода с ошибкой:

print('Hello!')

    print('Howdy!')

… еще:

if spam == 42:

    print('Hello!')

  print('Howdy!')

… еще:

if spam == 42:

print('Hello!')

4) Забыть вызвать len() в операторе цикла for. (Сообщение об ошибке: “TypeError: 'list' object cannot be interpreted as an integer”)

Обычно вы хотите перебирать индексы элементов в списке или строке, что требует вызова функции range(). Просто не забудьте передать возвращаемое значение len(someList) вместо передачи только someList.

Пример кода с ошикой:

spam = ['cat', 'dog', 'mouse']

for i in range(spam):

    print(spam[i])

(UPD: как некоторые указали, вам может понадобиться только for i in spam: вместо приведенного выше кода. Но вышесказанное относится к очень законному случаю, когда вам нужен индекс в теле цикла, а не только само значение.)

5) Попытка изменить строковое значение. (Сообщение об ошибке: “TypeError: 'str' object does not support item assignment”)

Строки являются неизменным типом данных. Пример кода с ошибкой:

spam = 'I have a pet cat.'

spam[13] = 'r'

print(spam)

Пример правильного варианта:

spam = 'I have a pet cat.'

spam = spam[:13] + 'r' + spam[14:]

print(spam)

6) Попытка объединить не строковое значение в строковое значение. (Сообщение об ошибке: “TypeError: Can't convert 'int' object to str implicitly”)

Пример кода с ошибкой:

numEggs = 12
print('I have ' + numEggs + ' eggs.')
Правильный вариант:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

… или:

numEggs = 12
print('I have %s eggs.' % (numEggs))

7) Пропуск кавычки, в начале или конце строкового значения. (Сообщение об ошибке: “SyntaxError: EOL while scanning string literal”)

Пример кода с ошикой:

print(Hello!')

… еще:

print('Hello!)
...еще:
myName = 'Al'
print('My name is ' + myName + . How are you?')

8) Опечатка в переменной или имени функции. (Сообщение об ошибке: “NameError: name 'fooba' is not defined”)

Пример кода с ошибкой:

foobar = 'Al'
print('My name is ' + fooba)
...еще:
spam = ruond(4.2)
...еще:
spam = Round(4.2)

9) Опечатка в названии метода. (Сообщение об ошибке: “AttributeError: 'str' object has no attribute 'lowerr'”)

Пример кода с ошибкой:

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()

10) Выход за пределы массива. (Сообщение об ошибке: “IndexError: list index out of range”)

Пример кода с ошибкой:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11) Использование несуществующего ключа словаря. (Сообщение об ошибке: “KeyError: 'spam'”)

Пример кода с ошибкой:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12) Попытка использовать ключевые слова Python в качестве переменной (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Ключевые слова Python (также называются зарезервированные слова) не могут быть использованы для названия переменных. Ошибка будет со следующим кодом:

class = 'algebra'

Ключевые слова Python 3: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13) Использование расширенного оператора присваивания для новой переменной. (Сообщение об ошибке: “NameError: name 'foobar' is not defined”)

Не думайте, что переменные начинаются со значения, такого как 0 или пустая строка. Выражение с расширенным оператором как spam += 1 эквивалентно spam = spam + 1. Это означает, что для начала в spam должно быть какое-то значение.

Пример кода с ошибкой:

spam = 0
spam += 42
eggs += 42

14) Использование локальных переменных (с таким же именем как и у глобальной переменной) в функции до назначения локальной переменной. (Сообщение об ошибке: “UnboundLocalError: local variable 'foobar' referenced before assignment”)

Использовать локальную переменную в функции, имя которой совпадает с именем глобальной переменной, довольно сложно. Правило таково: если переменной в функции когда-либо назначается что-то, она всегда является локальной переменной, когда используется внутри этой функции. В противном случае, это глобальная переменная внутри этой функции.
Это означает, что вы не можете использовать ее как глобальную переменную в функции до ее назначения.

Пример кода с ошибкой:

someVar = 42
def myFunction():
    print(someVar)
    someVar = 100
myFunction()

15) Попытка использовать range() для создания списка целых чисел. (Сообщение об ошибке: “TypeError: 'range' object does not support item assignment”)

Иногда вам нужен список целочисленных значений по порядку, поэтому range() кажется хорошим способом создать этот список. Однако вы должны помнить, что range() возвращает «объект диапазона», а не фактическое значение списка.

Пример кода с ошибкой:

spam = range(10)
spam[4] = -1
То что вы хотите сделать, выглядит так:
spam = list(range(10))
spam[4] = -1

(UPD: Это работает в Python 2, потому что Python 2’s range() возвращает список значений. Но, попробовав сделать это в Python 3, вы увидите ошибку.)

16) Нет оператора ++ инкремента или -- декремента. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Если вы пришли из другого языка программирования, такого как C++, Java или PHP, вы можете попытаться увеличить или уменьшить переменную с помощью ++ или --. В Python таких операторов нет.

Пример кода с ошибкой:

spam = 0
spam++
То что вы хотите сделать, выглядит так:
spam = 0
spam += 1

17) UPD: как указывает Luchano в комментариях, также часто забывают добавить self в качестве первого параметра для метода. (Сообщение об ошибке: «TypeError: TypeError: myMethod() takes no arguments (1 given)»)

Пример кода с ошибкой:

class Foo():
    def myMethod():
        print('Hello!')
a = Foo()
a.myMethod()

Краткое объяснение различных сообщений об ошибках приведено в Приложении D книги «Invent with Python».


image
Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:

  • Курс «Профессия Data Scientist» (24 месяца)
  • Курс «Профессия Data Analyst» (18 месяцев)
  • Курс «Python для веб-разработки» (9 месяцев)

Читать еще

  • 450 бесплатных курсов от Лиги Плюща
  • Бесплатные курсы по Data Science от Harvard University
  • 30 лайфхаков чтобы пройти онлайн-курс до конца
  • Самый успешный и самый скандальный Data Science проект: Cambridge Analytica

Are you looking for the solution of Python unexpected unindent error? This is one of the common python exceptions among developers. Let’s understand when it occurs? We will also see its solution in this article.

What is Python unexpected unindent exception?

Most of the python beginners face this problem. There are so many forms of Python unexpected unindent exception/error.  As most of the popular programming languages like Java, C, C + use curly braces to complete the program block. But Python programming language use indentation in the place of braces in program block.

Indentation in Python is nothing but the use of the white space according to the python syntax. If we make any mistake in python indentation, this Python unexpected unindent exception occurs.

Let’s know the cases of it.

Case 1: Improper use of white space

Here is the example of this indentation exception.

def fun_correct_Identation(): 
    print("I m learning Identation Exception") 
    print("correct Indentation ") 

fun_correct_Identation()

The above code sample demonstrates the correct use of Indentation in python.

correct Identation python

correct Identation python

Now we will know how the improper white space can generate IndentationError: unexpected indent. Let’s see the below example-

def fun_incorrect_Identation(): 
    print("I m learning Identation Exception") 
     print("incorrect Identation ")  

fun_incorrect_Identation()

Here is the error Exception for the above code.

Here we have used one extra white space.  For instance, This generates the above exception in the example.

unexpected indent python

unexpected indent python

Case 2: White space and Tab using Alternatively

White space and Tab have the almost same effect in plain text. But there is a huge difference in Python programming language.

Note –

  1. A conditional expression like if in python starts after a white space. If we do not provide proper spacing in that expression. This will again raise the Indentation Exception.
  2. Loop and so many codes blocks in python need proper spacing.

How to fix indentation error in python?

Most importantly, Using any IDE or python supportive text editor is really helpful in fixing indentation error in python. This IDE helps in clearly seeing the improper white space or incomplete code blocks. 

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

The IndentationError: Unexpected indent error indicates that you have added an excess indent in the line that the python interpreter unexpected to have. An unexpected indent in the Python code causes this indentation error. To overcome the Indentation error, ensure that the code is consistently indented and that there are no unexpected indentations in the code. This would fix the IndentationError: Unexpected indent error.

The IndentationError: Unexpected indent error occurs when you use too many indent at the beginning of the line. Make sure your code is indented consistently and that there are no unexpected indent in the code to resolve Indentation error. Python doesn’t have curly braces or keyword delimiter to differentiate the code blocks. In python, the compound statement and functions requires the indent to be distinguished from other lines. The unexpected indent in python causes IndentationError: Unexpected indent error.

The indent is known as the distance or number of empty spaces between the start of the line and the left margin of the line. Indents are not considered in the most recent programming languages such as java, c++, dot net, etc. Python uses the indent to distinguish compound statements and user defined functions from other lines.

Exception

The error message IndentationError: Unexpected indent indicates that there is an excess indent in the line that the python interpreter unexpected to have. The indentation error will be thrown as below.

 File "/Users/python/Desktop/test.py", line 2
    print "end of program";
    ^
IndentationError: unexpected indent

Root Cause

The root cause of the error message “IndentationError: Unexpected indent” is that you have added an excess indent in the line that the python interpreter unexpected to have. In order to resolve this error message, the unexpected indent in the code, such as compound statement, user defined functions, etc. must be removed.

Solution 1

The unexpected indent in the code must be removed. Walk through the code to trace the indent. If any unwanted indent is found, remove it. The lines inside blocks such as compound statements and user defined functions will normally have excess indents, spaces, tabs. This error “IndentationError: unexpected indent” is resolved if the excess indents, tabs, and spaces are removed from the code.

Program

print "a is greater";
	print "end of program";

Output

 File "/Users/python/Desktop/test.py", line 2
    print "end of program";
    ^
IndentationError: unexpected indent

Solution

print "a is greater";
print "end of program";

Output

a is greater
end of program
[Finished in 0.0s]

Solution 2

In the sublime Text Editor, open the python program. Select the full program by clicking on Cntr + A. The entire python code and the white spaces will be selected together. The tab key is displayed as continuous lines, and the spaces are displayed as dots in the program. Stick to any format you wish to use, either on the tab or in space. Change the rest to make uniform format. This will solve the error.

Program

a=10;
b=20;
if a > b:
	print "Hello World";      ----> Indent with tab
        print "end of program";    ----> Indent with spaces

Solution

a=10;
b=20;
if a > b:
	print "Hello World";      ----> Indent with tab
	print "end of program";    ----> Indent with tab

Solution 3

In most cases, this error would be triggered by a mixed use of spaces and tabs. Check the space for the program indentation and the tabs. Follow any kind of indentation. The most recent python IDEs support converting the tab to space and space to tabs. Stick to whatever format you want to use. This is going to solve the error.

Check the option in your python IDE to convert the tab to space and convert the tab to space or the tab to space to correct the error.

Solution 4

In the python program, check the indentation of compound statements and user defined functions. Following the indentation is a tedious job in the source code. Python provides a solution for the indentation error line to identify. To find out the problem run the python command below. The Python command shows the actual issue.

Command

python -m tabnanny test.py 

Example

$ python -m tabnanny test.py 
'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 3)
$ 

Solution 5

There is an another way to identify the indentation error. Open the command prompt in Windows OS or terminal command line window on Linux or Mac, and start the python. The help command shows the error of the python program.

Command

$python
>>>help("test.py")

Example

$ python
Python 2.7.16 (default, Dec  3 2019, 07:02:07) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help("test.py")
problem in test - <type 'exceptions.IndentationError'>: unindent does not match any outer indentation level (test.py, line 3)

>>> 
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> ^D

If you are new to coding or an experienced coder, you might have come across indentation error in python. It looks silly but it can pause the entire process and take good amount of time to fix it. I can help you saving some of your precious time. So, lets dive little deeper into it and understand what is indentation and how to fix it

Python is a procedural language. An indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The indentation error can occur when the spaces or tabs are not placed properly. There will not be an issue if the interpreter does not find any issues with the spaces or tabs. If there is an error due to indentation, it will come in between the execution and can be a show stopper.

Python follows the PEP8 whitespace ethics while arranging its code and therefore it is suggested that there should be 4 whitespaces between every iteration and any alternative that doesn’t have this will return an error.

Below are some of the common causes of an indentation error in Python:

  • While coding you are using both the tab as well as space. While in theory both of them serve the same purpose, if used alternatively in a code, the interpreter gets confused between which alteration to use and thus returns an error.

  • While programming you have placed an indentation in the wrong place. Since python follows strict guidelines when it comes to arranging the code, if you placed any indentation in the wrong place, the indentation error is mostly inevitable.

  • Sometimes in the midst of finishing a long program, we tend to miss out on indenting the compound statements such as for, while and if and this in most cases will lead to an indentation error.

  • Last but not least, if you forget to use user defined classes, then an indentation error will most likely pop up.

Errors due to indentation in Python:

Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a sub block. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).

Few tips to solve an indentation error in Python:

1. While there is no quick fix to this problem, one thing that you need to keep in mind while trying to find a solution for the indentation error is the fact that you have to go through each line individually and find out which one contains the error.

In Python, all the lines of code are arranged according to blocks, so it becomes easier for you to spot an error. For example, if you have used the if statement in any line, the next line must definitely have an indentation.

Take a look at the example below.

If you need guidance on how the correct form of indentation will look like, take a look at the example below.

2. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.

For Pycharm, please go to file — settings — editor — code style — python

3. Use the Python interpreter built-in Indent Guide. It takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors.

Conclusion:

Getting errors are inevitable part of programming, so is debugging. One cannot ignore indentation error while working with python but above tips show that it can be easily resolved. Hope this information makes your life little easy and programming journey more exciting.

References:

https://www.edureka.co/blog/indentation-error-in-python/

Python indentation is a part of the syntax. It’s not just for decoration.

You’ll learn what these errors mean and how to solve them:

  • IndentationError: unexpected indent
  • IndentationError: expected an indented block
  • IndentationError: unindent does not match any outer indentation level
  • IndentationError: unexpected unindent

So if you want to learn how to solve those errors, then you’re in the right place.

Let’s kick things off with error #1!

Polygon art logo of the programming language Python.

How to Solve IndentationError: unexpected indent in Python

Python is a beautiful language. One of the key features of this beauty is the lack of curly braces and other symbols that mark the beginning and end of each block. 

Even in C it is considered a good practice to indent, denoting different levels in the code. Compare the same C ++ code with and without indentation. First with the indentation:

#include <iostream>
#include <windows.h>
#include<time.h>
using namespace std;
void main()
{
    srand (unsigned (time(NULL)));
    int a,b,i;
    cout<<"Guess number game".nn";
    a=rand()%10+1;
    cout<<"AI conceived a number from 1 to 10.n";
    cout<<"Enter your guess and press <Enter>nn";
    for(i=1;i<3;i++)
    {
        cout<<"--->";
        cin>>b;
        if(b==a)
        {
            cout<<"You won! Congrats!n";
            cout<<"You guessed with "<<i<<" try!n";
            break;
        }
        if(b!=a)
        {
            cout<<"No, that's the other number. Try again!n";
        }
    }
    if(b!=a&&i==3)
    {
        cout<<"You lose!n";
    }
}

And the same code without indentation:

#include <iostream>
#include <windows.h>
#include<time.h>
using namespace std;
void main()
{
srand (unsigned (time(NULL)));
int a,b,i;
cout<<"Guess number gamen";
a=rand()%10+1;
cout<<"AI conceived a number from 1 to 10n";
cout<<"Enter your guess and press <Enter>n";
for(i=1;i<3;i++)
{
cout<<"--->";
cin>>b;
if(b==a)
{
cout<<"You won! Congrats!n";
cout<<"You guessed with "<<i<<" try!n";
break;
}
if(b!=a)
{
cout<<"No, that's the other number. Try again!n";
}
}
if(b!=a&&i==3)
{
cout<<"You lose!n";
}
}

Both codes will compile and run, but the indented code is a lot easier to read. In the second case, it isn’t clear which parenthesis goes with which. 

In Python, parentheses aren’t needed, but indentation is. This is what the C++ program would look like in Python:

from random import randint
print("Guess a number game!")
a = randint(1, 11)
print("AI conceived a number from 1 to 10")
print("Enter your guess and press <Enter>")
for i in range(3):
    b = int(input("-->"))
    if a == b:
        print("You won! Congrats!")
        print(f"You guessed with {i+1} try!")
        break
    else:
        print("No, that's the other number. Try again!")
else:
    print("You lose!")
Guess a number game!
AI conceived a number from 1 to 10
Enter your guess and press <Enter>
-->4
You won! Congrats!
You guessed with 1 try!

However, there is a downside to this beauty. If you make a mistake in the indentation, the program will be inconsistent, which will lead to errors when it’s running. 

Perhaps, this is a better option than changing the indentation and not getting the error, but changing the meaning of the program. 

The error IndentationError: unexpected indent is one that results from wrong indentation. It happens when there are no keywords in front of the indentation. Here’s an example:

name = "John Smith"
  print("Hi, ", name)
File "<ipython-input-2-0ae5732b16d5>", line 2
    print("Hi, ", name)
    ^
IndentationError: unexpected indent

Python expects a keyword line to come before an indented line. List of keywords followed by an indented line:

  • class: class definition
  • def: function definition
  • for: a loop with a parameter
  • while: a loop with a condition
  • if, elif, else: conditional operator
  • try, except, finally: exception handling
  • with: a context operator

Python warns you if it finds a line that’s indented, but the previous line doesn’t have these keywords.

How to Solve IndentationError: unexpected indent error in Python

You’ll get a similar error if you don’t indent after a keyword, here’s an example:

for _ in range(10):
print("Hello!")
File "<ipython-input-33-2c027d903716>", line 2
    print("Hello!")
        ^
IndentationError: expected an indented block

IndentationError: expected an indented block happens when you start a construct that assumes you have at least one indented block, but you didn’t indent this.

Tense and serious programmer looking at data on the computer.

This is an easy fix. Just indent a block that’s inside a loop or other appropriate construction.

Python uses spaces for indentation, and tabs are automatically converted to four spaces in Python 3 editors. 

Another feature is that the number of indent spaces can be any, but inside the block they’re the same. 

Since using different numbers of indentations can be confusing, PEP8 recommends exactly four spaces per level of indentation:

a = -1
if a > 0:
   print("Positive")
elif a < 0:
  print("Negative")
else:
 print("Zero")
Negative

This code is possible, it won’t cause an error, but it’ll make your code look terrible to people who’ll read it later.

Often, the IndentationError: unexpected indent error shows up when copying code from any source. 

This is a reason why you shouldn’t mindlessly copy-paste code from somewhere.When you borrow code, it’s always best to retype it.

So there won’t be as many errors when you run this code later. And you better understand what you copied. 

Even in your very first program, you can get this error if you copy the code along with the layout characters:


  print("Hello")
File "<ipython-input-16-c3b57afc4f5f>", line 2
    print("Hello")
    ^
IndentationError: unexpected indent

Another copying error can happen when you edit your code in a text editor without the ability to replace tabs with 4 spaces, such as Notepad++, and use both tabs and spaces for indentation. 

This error is the hardest to figure out because it looks like the code’s on the same line.

The first line has a tab and the second has 4 spaces, which is an entirely different level of indentation for a Python interpreter:

    print("Hello")
    print("World!")

For this error, you can either remove or replace all of the indents, or enable service characters, in Notepad++ this looks like this:

Screenshot Notepad++ Intend

Now you can just replace the tabs with spaces.

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

Another error that happens when copying code or when your attention wanders is IndentationError: unindent does not match any outer indentation level. Let’s look at some code that causes such an error:

a = 2
b = 3
for i in range(b):
    if a < i:
        print("Less")
    else:
        print("More")
   print("Round ", i, " finished!")

Draw vertical lines along the indentation levels. We have three indentation levels here: –

  • Original (no indentation)
  • First level is the block inside the loop
  • Second level is the block inside the conditional statement
screenshot_vertical_lines_python

When the lines are drawn, it becomes obvious that the indentation is not in line with the print statement. This line doesn’t belong to any of the existing indentation levels.

You need one more space, then the code will run:

a = 1
b = 3
for i in range(b):
    if a < i:
        print("Less")
    else:
        print("More")
    print("Round ", i, " finished!")
More
Round  0  finished!
More
Round  1  finished!
Less
Round  2  finished!

One way to get around this kind of error is to use automatic code formatters based on PEP8 standards, like autopep8 or Black.

These projects are not primarily intended to fix bugs, but to bring the code up to PEP8 standard, and to maintain code consistency in the project. 

Serious programmer creating a computer software.

When you start out with Python, it is helpful to use these utilities to make beautiful code. But you shouldn’t just do this carelessly. Pay attention to the inaccuracies that such utilities fix.

A much rarer error is IndentationError: unexpected unindent. Using the try-except operator causes it only under certain conditions. 

If you write try, you have to include the except keyword. But if you have just a try without an except, you get SyntaxError: invalid syntax:

try:
    print(0)
print(1)

But you’ll get an IndentationError: unexpected unindent if you try to use try-except inside a function, loop, condition, or context. 

The Python interpreter walks through the code and finds the try keyword, and searches down the except keyword lines at the same indentation level.

If it doesn’t find it, then it means the try-except operator hasn’t finished yet. Until the whole thing’s done, a line with a lower indentation level cannot appear. Here’s an example:

def multiply_by_two(x):
    try:
        return 2 * x
multiply_by_two(3)

This error is much less common and harder to find. Try must always have at least one except. If you don’t need to do anything on an exception, use the pass keyword.

def multiply_by_two(x):
    try:
        return 2 * x
    except:
        pass
multiply_by_two(3)
6

This isn’t great, but it is syntactically correct. 

Use accurate error definitions in your try-except statements, and don’t use empty excepts. If you’re trying to handle an exception, use at least BaseException.

Here’s more Python support:

  • 9 Examples of Unexpected Character After Line Continuation Character
  • 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed
  • How to Solve ‘Tuple’ Object Does Not Support Item Assignment
  • How to Solve SyntaxError: Invalid Character in Identifier
  • ImportError: Attempted Relative Import With No Known Parent Package

IndentationErrors serve two purposes: they help make your code more readable and ensure the Python interpreter correctly understands your code. If you add in an additional space or tab where one is not needed, you’ll encounter an “IndentationError: unexpected indent” error.

In this guide, we discuss what this error means and why it is raised. We’ll walk through an example of this error so you can figure out how you can fix it in your program.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

IndentationError: unexpected indent

An indent is a specific number of spaces or tabs denoting that a line of code is part of a particular code block. Consider the following program:

def hello_world():
	print("Hello, world!")

We have defined a single function: hello_world(). This function contains a print statement. To indicate to Python this line of code is part of our function, we have indented it.

You can indent code using spaces or tabs, depending on your preference. You should only indent code if that code should be part of another code block. This includes when you write code in:

  • An “if…else” statement
  • A “try…except” statement
  • A “for” loop
  • A “function” statement

Python code must be indented consistently if it appears in a special statement. Python enforces indentation strictly.

Some programming languages like JavaScript do not enforce indentation strictly because they use curly braces to denote blocks of code. Python does not have this feature, so the language depends heavily on indentation.

The cause of the “IndentationError: unexpected indent” error is indenting your code too far, or using too many tabs and spaces to indent a line of code.

The other indentation errors you may encounter are:

  • Unindent does not match any other indentation level
  • Expected an indented block

An Example Scenario

We’re going to build a program that loops through a list of purchases that a user has made and prints out all of those that are greater than $25.00 to the console.

To start, let’s define a list of purchases:

 purchases = [25.50, 29.90, 2.40, 57.60, 24.90, 1.55]

Next, we define a function to loop through our list of purchases and print the ones worth over $25 to the console:

def show_high_purchases(purchases):
	   for p in purchases:
		        if p > 25.00:
			            print("Purchase: ")
				                print(p)

The show_high_purchases() function accepts one argument: the list of purchases through which the function will search. The function iterates through this list and uses an if statement to check if each purchase is worth more than $25.00.

If a purchase is greater than $25.00, the statement Purchase: is printed to the console. Then, the price of that purchase is printed to the console. Otherwise, nothing happens.

Before we run our code, call our function and pass our list of purchases as a parameter:

show_high_purchases(purchases)

Let’s run our code and see what happens:

  File "main.py", line 7
	print(p)
	^
IndentationError: unexpected indent

Our code does not run successfully.

The Solution

As with any Python error, we should read the full error message to see what is going on. The problem appears to be on line 7, which is where we print the value of a purchase.

	if p > 25.00:
			print("Purchase: ")
				    print(p)

We have incidentally indented the second print() statement. This causes an error because our second print() statement is not part of another block of code. It is still part of our if statement.

To solve this error, we need to make sure that we consistently indent all our print() statements:

	if p > 25.00:
			print("Purchase: ")
			print(p)

Both print() statements should use the same level of indentation because they are part of the same if statement. We’ve made this revision above.

Let’s try to run our code:

Purchase:
25.5
Purchase:
29.9
Purchase:
57.6

Our code successfully prints out all the purchases worth more than $25.00 to the console.

Conclusion

“IndentationError: unexpected indent” is raised when you indent a line of code too many times. To solve this error, make sure all of your code uses consistent indentation and that there are no unnecessary indents.

Now you’re ready to fix this error like a Python expert!

Error messages in Python can often be confusing. Here is a list of common error messages you may find, along with a plain English explanation. These error messages are the result of runtime errors. They will immediately crash your Here are the error messages explained (your error messages may be slightly different but mean the same thing):

  • SyntaxError: invalid syntax
  • ImportError: No module named raandom
  • SyntaxError: EOL while scanning string literal
  • AttributeError: ‘str’ object has no attribute ‘lowerr’
  • IndentationError: expected an indented block
  • IndentationError: unexpected indent
  • IndentationError: unindent does not match any outer indentation level
  • TypeError: bad operand type for abs(): ‘str’
  • TypeError: abs() takes exactly one argument (2 given)
  • IndexError: list index out of range
  • KeyError: ‘spam’

SyntaxError: invalid syntax

This is the most generic error message the Python interpreter will give you. It means that Python was expecting something that isn’t there, or there is something there that it didn’t expect. Maybe you forgot to include or inserted an extra character. Here are some examples:

In the above case, the programmer used = (the assignment operator) instead of == (the equals comparator operator). Python never expects assignment statements where there should be a condition.

In the above case, the programmer forgot to match the ending ) closing parenthesis.

In the above case, the programmer forgot to put the colon at the end of the def statement. This can also happen with for, while, if, elif, and else statements.

ImportError: No module named raandom

This error shows up when you try to import a module that does not exist. Most likely, you have a typo in the module name. For example, you may have typed raandom instead of random.

SyntaxError: EOL while scanning string literal

print('Hello world!) 
print("Hello world!')

This error happens when you do not have two quote marks for a string, or you use different quote marks for the same string. Look at these two examples:

AttributeError: ‘str’ object has no attribute ‘lowerr’

'Hello'.lowerr() 'Hello'.append('x')

This error appears when you call a method or access an attribute that does not exist. This is most likely because 1) you have a typo in the method or attribute name, or 2) you are calling the method or attribute on a value that is the wrong data type. For example, strings have a method named lower(), but not lowerr() (that is a typo). And the append() method is a list method, so calling it on a string value will cause this error.

IndentationError: expected an indented block

def foo(): 
print('Hello world!')

This error happens if you fail to indent your code for a block. In the above example the print() call is at the same level of indentation as the def statement, when it should have a larger indentation.

IndentationError: unexpected indent

def foo():
   print('Hello world!') 
   print('Goodbye')

An unexpected indent error happens when you add an indentation for no reason. You should only add indentation after a def, if, else, elif, while, or for statment (or any statement that ends with a colon.)

IndentationError: unindent does not match any outer indentation level

def foo():
    print('Hello world!') 
    print('Goodbye')

This indentation error appears when you are decreasing the indentation, but not decreasing it to the same level as the previous indentation. The print(‘Goodbye’) call should either be at the same indentation as the other print() call (and be inside the if block) or at the same indentation as the if statement (and be outside of the if block).

TypeError: bad operand type for abs(): ‘str’

This error occurs when the value of an argument you pass to a function or method is of the wrong data type. In the above example, the abs() function takes an integer or floating point number. Passing a string for the argument results in an error.

TypeError: abs() takes exactly one argument (2 given)

This error appears when you pass the wrong number of arguments to a function or method, either too many or too few. The abs() function takes exactly one (and only one) argument. In our example we pass two arguments, which results in this error.

IndexError: list index out of range

myList = ['spam', 'fizz', 'eggs'] 
print(myList[3])

The IndexError happens when the index you use is larger than or equal to the number of actual items in the list. In our above example, the myList list only has 3 items in it, so the only valid indexes to use are 0, 1, and 2. The index 3 (or any other index larger than 2) is larger than any of these indexes, so the code results in an IndexError.

KeyError: ‘spam’

myDict = {'fizz':42, 'eggs':100} 
myDict['spam']

The KeyError happens when you try to access a key in a dictionary object that does not exist. Either the key was never added to the dictionary, was deleted previously with the del operator, or the key you are using has a typo in it.

Понравилась статья? Поделить с друзьями:
  • Indentationerror unexpected indent ошибка питон
  • Indentationerror unexpected indent как исправить
  • Indentationerror unexpected indent python ошибка
  • Indentationerror expected an indented block python ошибка
  • Indentation error unindent does not match any outer indentation level