Python unexpected indent что за ошибка
Перейти к содержимому

Python unexpected indent что за ошибка

What should I do with "Unexpected indent" in Python?

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

user avatar

18 Answers 18

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g., the if, while, and for statements). All lines of code in a block must start with exactly the same string of whitespace. For instance:

This one is especially common when running Python interactively: make sure you don’t put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)

Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?

Expected an indented block. 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 statements, or a function definition).

If you want a function that doesn’t do anything, use the "no-op" command pass:

Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces.

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.

Почему возникает ошибка IndentationError: unexpected indent?

Установил питон под Windows 10 64bit. Работает на Anaconda. Окружение python 3.4. Установил theano.

import theano работает при построчном вводе в консоль.
Когда пытаюсь запустить любой файл с примером, с theano связи нету.

введите сюда описание изображения

user avatar

user avatar

Если бы вы перевели текст ошибки, вы бы поняли, что у вас проблема с отступами.
Обратите внимание на отступ перед import .

Напоминаю, что в python блоки кода разграничиваются отступами.

Если питон счёл, что у вас вложенность кода обозначается четырьмя пробелами, а именно эта строка отбита одним табом, то будет такая ошибка.

Python IndentationError: unexpected indent Solution

James Gallagher

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.

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:

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:

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.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

The other indentation errors you may encounter are:

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:

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

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:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *