Python ошибка отступа неожиданный отступ

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:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

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!)

>>>   print "hello"
IndentationError: unexpected indent

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?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

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).

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

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

>>> def foo():
...     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. Don’t mix tabs and spaces. Most editors allow automatic replacement of one with the other. If you’re in a team, or working on an open-source project, see which they prefer.

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? там не перемешаны пробелы и табы, я пробовал и 4 пробела везде проставить и табы, ошибка одна( код вообще рандомный, просто для проверки сделал)

df = (200, 300)
	print('обычный форма:')
	print(df)

df = (300, 400)
	print('nмодернизация:')
	print(df)


  • Вопрос задан

    22 мар.

  • 4921 просмотр

Так и пишет, неожиданный отступ.

Если код так и выглядит

df = (200, 300)
  print('обычный форма:')
  print(df)

df = (300, 400)
  print('nмодернизация:')
  print(df)

То ошибка вполне логична, перед print() зачем-то стоят отступы, которых быть не должно

Пригласить эксперта


  • Показать ещё
    Загружается…

04 июн. 2023, в 12:23

30000 руб./за проект

04 июн. 2023, в 12:18

20000 руб./за проект

04 июн. 2023, в 12:07

2000 руб./за проект

Минуточку внимания

Автор оригинала: Chris.

Если вы похожи на меня, вы сначала попробуйте все в своем коде и исправить ошибки, как они приходят. Одна частая ошибка в Python – IndentationError: неожиданный отступ Отказ Итак, что означает это сообщение об ошибке?

Ошибка . IndentationError: неожиданный отступ Возникает, если вы используете непоследовательную отступ вкладок или пробелы для блоков кода с отступом, таких как Если блок и для петля. Например, Python бросит ошибку вдавливания, если вы используете для петля с три персонажа пробелов Отступ для первой строки и Один символ вкладок отступ второй строки корпуса петли. Чтобы устранить ошибку, используйте одинаковое количество пустых пробелов для всех блоков кода с отступом.

Давайте посмотрим на пример, где возникает эта ошибка:

for i in range(10):
  print(i)
   print('--')

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

Чтобы исправить ошибку, просто используйте одинаковое количество пробелов для каждой строки кода:

for i in range(10):
    print(i)
    print('--')

Общая рекомендация состоит в том, чтобы использовать четыре единственных пробелных персонажей '' для каждого Отступ уровень. Если у вас вложенные уровни вдавливания, это означает, что второй уровень вдавливания имеет одновение пробелы:

for i in range(10):
    for j in range(10):
        print(i, j)

Смесительные вкладки и пробелы частоты часто вызывают ошибку

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

На первый взгляд углубление выглядит одинаково. Однако, если вы пройдете пробелы перед Печать (I) , вы видите, что он состоит только из одного табличного характера, в то время как пробелы перед Распечатать (j) Заявление состоит из ряда пустых мест '' Отказ

Попробуйте сами: Прежде чем я скажу вам, что делать с этим, попробуйте исправить код себя в нашей интерактивной оболочке Python:

Упражнение : Исправьте код в оболочке интерактивного кода, чтобы избавиться от сообщения об ошибке.

Вы хотите развивать навыки Хорошо округлый Python Professional То же оплачивается в процессе? Станьте питоном фрилансером и закажите свою книгу Оставляя крысиную гонку с Python На Amazon ( Kindle/Print )!

Как исправить ошибку отступа на все времена?

Источник ошибки часто является неправильным использованием вкладок и пробеловных символов. Во многих редакторах кода вы можете установить символ вкладки на фиксированное количество символов пробела. Таким образом, вы, по сути никогда не используете сам табличный символ. Например, если у вас есть Sublime Text Editor, следующее быстрое руководство гарантирует, что вы никогда не будете работать в этой ошибке:

  • Установить Возвышенный текст Использовать вкладки для отступа: Вид -> Отступ -> Преобразовать вдавшиеся вкладки
  • Снимите флажок Опция Отступ с использованием пробелов в том же подменю выше.

Куда пойти отсюда?

Достаточно теории, давайте познакомимся!

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

Практические проекты – это то, как вы обостряете вашу пилу в кодировке!

Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?

Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.

Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.

Присоединяйтесь к свободному вебинару сейчас!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python One-listers (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

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

Here is my code … I am getting indentation error but i don’t know why it occurs.

->

# loop
while d <= end_date:
    # print d.strftime("%Y%m%d")
    fecha = d.strftime("%Y%m%d")
    # set url
    url = 'http://www.wpemergencia.omie.es//datosPub/marginalpdbc/marginalpdbc_' + fecha + '.1'
    # Descargamos fichero
    response = urllib2.urlopen(url)
    # Abrimos fichero
    output = open(fname,'wb')
    # Escribimos fichero
    output.write(response.read())
    # Cerramos y guardamos fichero
    output.close()
    # fecha++
    d += delta

Rory Daulton's user avatar

Rory Daulton

21.8k6 gold badges41 silver badges48 bronze badges

asked Dec 26, 2011 at 10:03

miguelfg's user avatar

3

Run your program with

python -t script.py

This will warn you if you have mixed tabs and spaces.

On *nix systems, you can see where the tabs are by running

cat -A script.py

and you can automatically convert tabs to 4 spaces with the command

expand -t 4 script.py > fixed_script.py

PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won’t get this problem with a programming editor.

PPS. For emacs users, M-x whitespace-mode will show the same info as cat -A from within an emacs buffer!

answered Dec 26, 2011 at 10:08

unutbu's user avatar

unutbuunutbu

833k182 gold badges1771 silver badges1660 bronze badges

3

find all tabs and replaced by 4 spaces in notepad ++ .It worked.

answered May 15, 2013 at 21:31

user2287824's user avatar

user2287824user2287824

1012 silver badges4 bronze badges

1

Check if you mixed tabs and spaces, that is a frequent source of indentation errors.

Daniel Fischer's user avatar

answered Dec 26, 2011 at 10:05

ilstam's user avatar

ilstamilstam

1,4534 gold badges18 silver badges32 bronze badges

You can’t mix tab and spaces for identation. Best practice is to convert all tabs to spaces.

How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don’t mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.

Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn’t match the following identations!

Velociraptors's user avatar

answered Dec 26, 2011 at 10:10

Don Question's user avatar

Don QuestionDon Question

11.1k5 gold badges36 silver badges53 bronze badges

Simply copy your script and put under «»» your entire code «»» …

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

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 using ctrl+b, now it will print indented code in console. that’s it

answered Feb 11, 2016 at 12:39

Mohideen bin Mohammed's user avatar

Table of Contents
Hide
  1. What are the reasons for IndentationError: unexpected indent?
    1. Python and PEP 8 Guidelines 
  2. Solving IndentationError: expected an indented block
  3. Example 1 – Indenting inside a function
  4. Example 2 – Indentation inside for, while loops and if statement
  5. Conclusion

Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.

What are the reasons for IndentationError: unexpected indent?

IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.

Python and PEP 8 Guidelines 

  1. Generally, in Python, you follow the four spaces rule according to PEP 8 standards
  2. Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
  3. Do not mix tabs and spaces. Python disallows the mixing of indentation.
  4. Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.

Solving IndentationError: expected an indented block

Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.

Example 1 – Indenting inside a function

Lines inside a function should be indented one level more than the “def functionname”. 

# Bad indentation inside a function

def getMessage():
message= "Hello World"
print(message)
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 2
    message= "Hello World"
    ^
IndentationError: expected an indented block

Correct way of indentation while creating a function.

# Proper indentation inside a function

def getMessage():
    message= "Hello World"
    print(message)
  
getMessage()

# Output
Hello World

Example 2 – Indentation inside for, while loops and if statement

Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.

Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.

# Bad indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
    print ("Hello world")
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 4
    print ("Hello world")
    ^
IndentationError: expected an indented block

To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.

# Proper indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
        print ("Hello world")
  
getMessage()

# Output
Hello world

Conclusion

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.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

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!

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

Введение

Примеры

IndentationErrors (или отступ SyntaxErrors)

В большинстве других языков отступ не является обязательным, но в Python (и других языках: ранних версиях FORTRAN, Makefiles, Whitespace (эзотерический язык) и т. Д.) Это не так, что может сбивать с толку, если вы пришли с другого языка если вы копировали код из примера в свой собственный, или просто если вы новичок.

IndentationError / SyntaxError: неожиданный отступ

Это исключение возникает, когда уровень отступа увеличивается без причины.

пример

Там нет причин для повышения уровня здесь:

print «Эта строка в порядке» print «Эта строка не в порядке»  print(«Эта строка не в порядке») print(«Эта строка не в порядке»)

Здесь есть две ошибки: последняя и что отступ не соответствует ни одному уровню отступа. Однако показано только одно:

print «Эта строка в порядке» print «Эта строка не в порядке»  print(«Эта строка не в порядке») print(«Эта строка не в порядке»)

IndentationError / SyntaxError: unindent не соответствует ни одному внешнему уровню отступа

Похоже, вы не удалили полностью.

пример

def foo (): print «Это должно быть частью foo ()» print «ERROR!» print «Это не часть foo ()»  print(«Эта строка не в порядке») print(«Эта строка не в порядке»)

IndentationError: ожидается блок с отступом

После двоеточия (а затем и новой строки) уровень отступа должен увеличиться. Эта ошибка возникает, когда этого не произошло.

пример

 if ok:
doStuff()

 

Примечание: Используйте ключевое слово pass (что не делает абсолютно ничего) просто Погружает if , else , за except , class , method или definition , но не сказать , что произойдет , если называется / условие истинно (но сделать это позже, или в случае за except : просто ничего не делать):

 def foo():
    pass

 

IndentationError: противоречивое использование табуляции и пробелов в отступе

пример

 def foo():
    if ok:
      return "Two != Four != Tab"
        return "i dont care i do whatever i want"

 

Как избежать этой ошибки

Не используйте вкладки. Это обескураживает PEP8 , в стиль руководства для Python.

  1. Установите редактор использовать 4 пробелов для отступа.
  2. Сделайте поиск и замените, чтобы заменить все вкладки с 4 пробелами.
  3. Убедитесь , что ваш редактор настроен на отображение вкладок в 8 пробелов, так что вы можете легко реализовать эту ошибку и исправить ее.

Смотрите этот вопрос , если вы хотите , чтобы узнать больше.

TypeErrors

Эти исключения возникают, когда тип какого-либо объекта должен быть другим

Ошибка типа: [определение / метод] занимает? позиционные аргументы, но? был дан

Функция или метод вызывались с большим (или меньшим) количеством аргументов, чем те, которые он может принять.

пример

Если дано больше аргументов:

 def foo(a): return a
foo(a,b,c,d) #And a,b,c,d are defined

 

Если дано меньше аргументов:

 def foo(a,b,c,d): return a += b + c + d
foo(a) #And a is defined

 

Примечание: если вы хотите использовать неизвестное количество аргументов, вы можете использовать *args или **kwargs.См * арг и ** kwargs

Ошибка типа: неподдерживаемые типы операндов для [операнд]: ‘???’ а также ‘???’

Некоторые типы не могут работать вместе, в зависимости от операнда.

пример

Например: + используется для конкатенации и добавить, но вы не можете использовать любой из них для обоих типов. Например, пытаясь сделать set путем конкатенации ( + ю) 'set1' и 'tuple1' дает ошибку. Код:

 set1, tuple1 = {1,2}, (3,4)
a = set1 + tuple1

 

Некоторые виды (например: int и string ) используют как + , но и для различных вещей:

 b = 400 + 'foo'

 

Или они могут даже не использоваться ни для чего:

 c = ["a","b"] - [1,2]

 

Но вы можете, например , добавить float к int :

 d = 1 + 1.0

 

Ошибка типа: ‘???’ объект не повторяем / подписан:

Для объекта быть итерацией он может принимать последовательные индексы , начиная с нуля , пока индексы больше не действительны и IndexError поднято (Технически: он должен иметь __iter__ метод , который возвращает __iterator__ , или который определяет __getitem__ метод , который делает что было упомянуто ранее).

пример

Здесь мы говорим , что bar является нулевым пунктом 1. Глупости:

 foo = 1
bar = foo[0]

 

Это более дискретный вариант: В этом примере for пытается установить x , чтобы amount[0] , первый элемент в качестве итератора , но он не может , поскольку количество представляет собой INT:

 amount = 10
for x in amount: print(x)

 

Ошибка типа: ‘???’ объект не вызывается

Вы определяете переменную и вызываете ее позже (например, что вы делаете с функцией или методом)

пример

 foo = "notAFunction"
foo()

 

NameError: name ‘???’ не определено

Возникает, когда вы пытались использовать переменную, метод или функцию, которые не инициализированы (по крайней мере, до этого). Другими словами, оно возникает, когда запрошенное локальное или глобальное имя не найдено. Вполне возможно , что вы орфографические ошибки имени объекта или забыли import что — то. Также возможно это в другом объеме. Мы рассмотрим их на отдельных примерах.

Это просто не определено нигде в коде

Возможно, вы забыли инициализировать его, особенно если это константа

 foo   # This variable is not defined
bar() # This function is not defined

 

Может быть, это будет определено позже:

 baz()

def baz():
    pass

 

Или это не import изд:

 #needs import math

def sqrt():
    x = float(input("Value: "))
    return math.sqrt(x)


 

Области применения Python и правило LEGB:

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

 Local → Enclosed → Global → Built-in.

 
  • L OCAL: Переменные не объявляются глобальные или назначены в функции.
  • Е nclosing: Переменные , определенные в функции , которая намотана внутри другой функции.
  • G ЛОБАЛЬНЫЕ: Переменные , объявленные глобальные или назначены на верхнем уровне файла.
  • B uilt в: Переменные в наперед заданные имена встроенных модуля.

В качестве примера:

 for i in range(4):
    d = i * 2
print(d)

 

d является доступным , поскольку for цикла не ознаменует новую сферу, но если это так, то мы имели бы ошибку и его поведение будет выглядеть следующим образом:

 def noaccess():
    for i in range(4):
        d = i * 2
noaccess()
print(d)

 

Python говорит NameError: name 'd' is not defined

Другие ошибки

AssertError

assert утверждение существует практически в каждом языке программирования. Когда вы делаете:

 assert condition

 

или же:

 assert condition, message

 

Это эквивалентно этому:

 if __debug__:
    if not condition: raise AssertionError(message)

 

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

Примечание: встроенная переменная отладки Правда при нормальных условиях, Ложные при оптимизации запрашиваемых (опция командной строки -O). Задания для отладки являются незаконными. Значение для встроенной переменной определяется при запуске интерпретатора.

KeyboardInterrupt

Ошибка возникает , когда пользователь нажимает клавишу прерывания обычно Ctrl + C или дель.

ZeroDivisionError

Вы пытались вычислить 1/0 , который не определен. Посмотрите этот пример, чтобы найти делители числа:

div = float (raw_input («Divisors of:»)) для x в xrange (div + 1): # включает само число и ноль, если div / x == div // x: print x, «является делителем» Div  div = int (input («Divisors of:»)) для x в диапазоне (div + 1): # включает само число и ноль, если div / x == div // x: print(x, «является делителем», див)  Он вызывает `ZeroDivisionError`, потому что цикл` for` присваивает это значение `x`. Вместо этого должно быть:  div = float (raw_input («Divisors of:»)) для x в xrange (1, div + 1): # включает в себя само число, но не ноль, если div / x == div // x: print x, «является делитель», див  div = int (input («Divisors of:»)) для x в диапазоне (1, div + 1): # включает само число, но не ноль, если div / x == div // x: print(x, «is делитель», div)

Синтаксическая ошибка в хорошем коде

В большинстве случаев ошибка SyntaxError, указывающая на неинтересную строку, означает, что в строке перед ней есть проблема (в данном примере это пропущенная скобка):

 def my_print():
    x = (1 + 1
    print(x)

 

Возвращает

   File "<input>", line 3
    print(x)
        ^
SyntaxError: invalid syntax

 

Как показано в примере, наиболее распространенной причиной этой проблемы являются несоответствующие скобки / скобки.

В Python 3 есть одно важное предупреждение для операторов печати:

>>> распечатать «Привет мир» Файл » «, строка 1 print» hello world «^ SyntaxError: неверный синтаксис, поскольку [оператор` print` был заменен функцией `print()`] (https://docs.python.org/3/whatsnew/3.0.html # print-is-a-function), так что вы хотите: print(«hello world») # Обратите внимание, что это справедливо как для Py2, так и для Py3

Синтаксис

Параметры

Примечания

Понравилась статья? Поделить с друзьями:
  • Python ошибка доступа
  • Python ошибка takes no arguments
  • Python ошибка random
  • Python ошибка memory error
  • Python ошибка math domain error