Index expected python ошибка

Dynamo

Loading

  • Learn
  • Explore
  • Blog
  • Forum
  • Roadmap
  • Resources

    • Primer
    • Dictionary
    • Developer
    • Builds
    • Events
    • DesignScript Guide
    • Help Center
  • Get Dynamo
  • Privacy

Objects in Python do not automatically support slice notation just because they support indexing. That has to be programmed in. There may be syntax more convenient than what you’re using though.

If it’s iterable, you can convert to a list first, and then slice it, like

a = [*x][1:]

For especially large iterables (does not seem to be the case here), this may be inefficient. In that case, islice it before you unpack into the list.

from itertools import islice
a = [*islice(x, 1, None)]

But objects do not automatically support iteration just because they support indexing either. If that’s the case, you can still iterate manually with range() and a comprehension,

a = [x[i] for i in range(1, len(x))]

Though this isn’t really shorter until you have a few more elements to deal with. If you need this pattern a lot you could abstract it into a function.

And finally, objects do not necessarily support len just because they support indexing. If you don’t know the length in advance, about all you can do is loop through and catch the LookupError at that point.

Jan 12, 2018 10:00:10 AM |
Python Exception Handling: IndexError

A look at the IndexError in Python, with code samples illustrating the basic use of lists, and how invalid indices can raise IndexErrors.

Moving right along through our in-depth Python Exception Handling series, today we’ll be going over the IndexError, in all its glory. The IndexError is one of the more basic and common exceptions found in Python, as it is raised whenever attempting to access an index that is outside the bounds of a list.

In today’s article we’ll examine the IndexError in more detail, starting with where it resides in the larger Python Exception Class Hierarchy. We’ll also look into some functional Python sample code that will illustrate how basic lists are used and improper indexing can lead to IndexErrors. Let’s get into it!

The Technical Rundown

All Python exceptions inherit from the BaseException class, or extend from an inherited class therein. The full exception hierarchy of this error is:

  • BaseException
    • Exception
      • LookupError
        • IndexError

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

# main.py
import datetime

from gw_utility.book import Book
from gw_utility.logging import Logging

def main():
try:
# Create list and populate with Books.
books = list()
books.append(Book("Shadow of a Dark Queen", "Raymond E. Feist", 497, datetime.date(1994, 1, 1)))
books.append(Book("Rise of a Merchant Prince", "Raymond E. Feist", 479, datetime.date(1995, 5, 1)))
books.append(Book("Rage of a Demon King", "Raymond E. Feist", 436, datetime.date(1997, 4, 1)))

# Output Books in list, with and without index.
Logging.line_separator('Books')
log_list(books)
Logging.line_separator('Books w/ index')
log_list(books, True)
# Output list element outside bounds.
Logging.line_separator('books[len(books)]')
Logging.log(f'books[{len(books)}]: {books[len(books)]}')
except IndexError as error:
# Output expected IndexErrors.
Logging.log_exception(error)
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)

def log_list(collection, include_index=False):
"""Logs the each element in collection to the console.

:param collection: Collection to be iterated and output.
:param include_index: Determines if index is also output.
:return: None
"""
try:
# Iterate by converting to enumeration.
for index, item in enumerate(collection):
if include_index:
Logging.log(f'collection[{index}]: {item}')
else:
Logging.log(item)
except IndexError as error:
# Output expected IndexErrors.
Logging.log_exception(error)
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)

if __name__ == "__main__":
main()

# book.py
import datetime

class Book:
author: str
page_count: int
publication_date: datetime.date
title: str

def __eq__(self, other):
"""Determines if passed object is equivalent to current object."""
return self.__dict__ == other.__dict__

def __init__(self,
title: str = None,
author: str = None,
page_count: int = None,
publication_date: datetime.date = None):
"""Initializes Book instance.

:param title: Title of Book.
:param author: Author of Book.
:param page_count: Page Count of Book.
:param publication_date: Publication Date of Book.
"""
self.author = author
self.page_count = page_count
self.publication_date = publication_date
self.title = title

def __getattr__(self, name: str):
"""Returns the attribute matching passed name."""
# Get internal dict value matching name.
value = self.__dict__.get(name)
if not value:
# Raise AttributeError if attribute value not found.
raise AttributeError(f'{self.__class__.__name__}.{name} is invalid.')
# Return attribute value.
return value

def __len__(self):
"""Returns the length of title."""
return len(self.title)

def __str__(self):
"""Returns a formatted string representation of Book."""
date = '' if self.publication_date is None else f', published on {self.publication_date.__format__("%B %d, %Y")}'
return f''{self.title}' by {self.author} at {self.page_count} pages{date}.'

# logging.py
import math
import sys
import traceback

class Logging:
separator_character_default = '-'
separator_length_default = 40

@classmethod
def __output(cls, *args, sep: str = ' ', end: str = 'n', file=None):
"""Prints the passed value(s) to the console.

:param args: Values to output.
:param sep: String inserted between values, default a space.
:param end: String appended after the last value, default a newline.
:param file: A file-like object (stream); defaults to the current sys.stdout.
:return: None
"""
print(*args, sep=sep, end=end, file=file)

@classmethod
def line_separator(cls, value: str = None, length: int = separator_length_default,
char: str = separator_character_default):
"""Print a line separator with inserted text centered in the middle.

:param value: Inserted text to be centered.
:param length: Total separator length.
:param char: Separator character.
"""
output = value

# If no value passed, output separator of length.
if value == None or len(value) == 0:
output = f'{char * length}'
elif len(value) < length:
# Update length based on insert length, less a space for margin.
length -= len(value) + 2
# Halve the length and floor left side.
left = math.floor(length / 2)
right = left
# If odd number, add dropped remainder to right side.
if length % 2 != 0:
right += 1

# Surround insert with separators.
output = f'{char * left} {value} {char * right}'

cls.__output(output)

@classmethod
def log(cls, *args, sep: str = ' ', end: str = 'n', file=None):
"""Prints the passed value(s) to the console.

:param args: Values to output.
:param sep: String inserted between values, default a space.
:param end: String appended after the last value, default a newline.
:param file: A file-like object (stream); defaults to the current sys.stdout.
"""
cls.__output(*args, sep=sep, end=end, file=file)

@classmethod
def log_exception(cls, exception: BaseException, expected: bool = True):
"""Prints the passed BaseException to the console, including traceback.

:param exception: The BaseException to output.
:param expected: Determines if BaseException was expected.
"""
output = "[{}] {}: {}".format('EXPECTED' if expected else 'UNEXPECTED', type(exception).__name__, exception)
cls.__output(output)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback)

When Should You Use It?

Since the IndexError is raised when dealing with lists, our code sample is setup to handle the basic creation and iteration of a list of Books. The log_list(collection, include_index=False) method iterates through the passed collection list by converting to an enumeration, then outputting each item (with or without the index):

def log_list(collection, include_index=False):
"""Logs the each element in collection to the console.

:param collection: Collection to be iterated and output.
:param include_index: Determines if index is also output.
:return: None
"""
try:
# Iterate by converting to enumeration.
for index, item in enumerate(collection):
if include_index:
Logging.log(f'collection[{index}]: {item}')
else:
Logging.log(item)
except IndexError as error:
# Output expected IndexErrors.
Logging.log_exception(error)
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)

To test this out we start by creating a new list and appending a handful of books (from a great fantasy series, by the way) onto it:

# Create list and populate with Books.
books = list()
books.append(Book("Shadow of a Dark Queen", "Raymond E. Feist", 497, datetime.date(1994, 1, 1)))
books.append(Book("Rise of a Merchant Prince", "Raymond E. Feist", 479, datetime.date(1995, 5, 1)))
books.append(Book("Rage of a Demon King", "Raymond E. Feist", 436, datetime.date(1997, 4, 1)))

Now, we need to pass our books list to the log_list(...) method, so we’ll confirm that both the basic and index-included outputs work:

# Output Books in list, with and without index.
Logging.line_separator('Books')
log_list(books)
Logging.line_separator('Books w/ index')
log_list(books, True)

As expected, this code works as it should and outputs the following Book details to the console:

---------------- Books -----------------
'Shadow of a Dark Queen' by Raymond E. Feist at 497 pages, published on January 01, 1994.
'Rise of a Merchant Prince' by Raymond E. Feist at 479 pages, published on May 01, 1995.
'Rage of a Demon King' by Raymond E. Feist at 436 pages, published on April 01, 1997.
------------ Books w/ index ------------
collection[0]: 'Shadow of a Dark Queen' by Raymond E. Feist at 497 pages, published on January 01, 1994.
collection[1]: 'Rise of a Merchant Prince' by Raymond E. Feist at 479 pages, published on May 01, 1995.
collection[2]: 'Rage of a Demon King' by Raymond E. Feist at 436 pages, published on April 01, 1997.

Just like arrays and other common collections in programming, Python lists are zero-indexed, so our three elements are only indexed up to a maximum of 2. However, let’s see what happens if we try to access index 3 of the books list:

# Output list element outside bounds.
Logging.line_separator('books[len(books)]')
Logging.log(f'books[{len(books)}]: {books[len(books)]}')

As you probably suspect, this raises an IndexError, indicating that the list index is out of range:

---------- books[len(books)] -----------
[EXPECTED] IndexError: list index out of range
File "D:workAirbrake.ioExceptionsPythonBaseExceptionExceptionLookupErrorIndexErrormain.py", line 23, in main
Logging.log(f'books[{len(books)}]: {books[len(books)]}')

Airbrake’s robust error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices! Try Airbrake for free with a 14-day trial.

Программирование, 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

Содержание

  • Заголовок
    • Чтение Traceback 1
    • Чтение Traceback 2
  • Некоторые ошибки с примерами кода
    • Ошибки в синтаксисе
    • Ошибки в логике
  • Контест №1

Заголовок

Создайте файл solution.py со следующим кодом:

for coord in vector:
    print(coord)

Наш код подразумевает печать содержимого переменной vector.

Запустим написанный скрипт, получим следующий вывод:

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 1, in <module>
    for coord in vector:
NameError: name 'vector' is not defined

Сообщение означает, что при исполнении кода возникла ошибка.
При этом Python сообщает нам кое-что ещё.
Разберём это сообщение детально.

Чтение Traceback 1

Исходное сообщение нужно мысленно разделить на две части.
Первая часть это traceback-сообщение:

Traceback (most recent call last):
  File "solution.py", line 1, in <module>
    for coord in vector:

Вторая часть — сообщение о возникшей ошибке:

NameError: name 'vector' is not defined

Разберём первую часть.
Traceback в грубом переводе означает «отследить назад».
Traceback показывает последовательность/стэк вызовов, которая, в конечном итоге, вызвала ошибку.

Первая строка:

Traceback (most recent call last):

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

Вторая и третья строки:

File "solution.py", line 1, in <module>
  for coord in vector:

показывают информацию о вызове (в нашем случае он один).
Во-первых, здесь есть информация о файле, в котором произошёл вызов («solution.py»), затем указан номер строки, где этот вызов происходит («line 1»), в конце стоит информация о том, откуда произошёл вызов («<module>»).
В нашем случае вызов происходит непосредственно из модуля, т.е. не из функции.
Наконец, вывод содержит не только номер строки, но и саму строку «for coord in vector:».

Заключительная строка сообщения:

NameError: name 'vector' is not defined

содержит вид (тип) ошибки («NameError»), и после двоеточия содержит подсказку.
В данном случае она означает, что имя «vector» не определено.

В самом деле, если взглянуть снова на код, то можно убедиться, что мы нигде не объявили переменную «vector».

Подведём итоги.
При попытке запуска мы получили следующий вывод

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 1, in <module>
    for coord in vector:
NameError: name 'vector' is not defined

Он говорит нам о возникновении ошибки.
Эта ошибка обнаружилась интерпретатором в первой строке файла «solution.py».
Сама ошибка является ошибкой имени и указывает на необъявленное имя — «vector».

Чтение Traceback 2

Оберните код из solution.py в функцию:

def print_vector(vector):
    for coord in vector:
        print(coord)

print_vector(5)

Запустим наш код

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 5, in <module>
    print_vector(5)
  File "solution.py", line 2, in print_vector
    for coord in vector:
TypeError: 'int' object is not iterable

На этот раз сообщение об ошибке сложнее, однако структура у него та же.

Часть со стеком вызовов увеличилась:

Traceback (most recent call last):
  File "solution.py", line 5, in <module>
    print_vector(5)
  File "solution.py", line 2, in print_vector
    for coord in vector:

Поскольку «most recent call last», читать будем её сверху вниз.

Вызовов на этот раз два.
Первый вызов:

File "solution.py", line 5, in <module>
  print_vector(5)

Произошел в пятой строке.
Судя по строчке кода, это вызов написанной нами функции print_vector(5) с аргументом 5.

Следом за ней второй вызов:

File "solution.py", line 2, in print_vector
  for coord in vector:

Этот вызов происходит внутри функции print_vector, содержащейся в файле «solution.py».
Вызов находится в строке 2.

Сама же ошибка имеет вид:

TypeError: 'int' object is not iterable

Как и в первом примере, сообщение об ошибке содержит её тип и подсказку.
В нашем случае произошла ошибка типа.
В подсказке же указано, что объект типа int не является итерируемым, т.е. таким объектом, который нельзя использовать в цикле for.

Итог:

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 5, in <module>
    print_vector(5)
  File "solution.py", line 2, in print_vector
    for coord in vector:
TypeError: 'int' object is not iterable

В нашем коде возникла ошибка.
Её вызвала последовательность вызовов.
Первый вызов произошел непосредственно из модуля — в строке 5 происходит вызов функции print_vector(5).
Внутри этой функции ошибка возникла в строчке 2, содержащей проход по циклу.
Сообщение об ошибке означает, что итерироваться по объекту типа int нельзя.
В нашем случае мы вызвали функцию print_vector от числа (от 5).

Некоторые ошибки с примерами кода

Ошибки в синтаксисе

Наиболее частая ошибка, которая возникает в программах на Python — SyntaxError: когда какое-то утверждение записано не по правилам языка, например:

$ python3
>>> print "hello"
  File "<stdin>", line 1
    print "hello"
                ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?

Тот же тип ошибки возникнет, если забыть поставить двоеточие в цикле:

$ python3
>>> for i in range(5)
  File "<stdin>", line 1
    for i in range(5)
                ^
SyntaxError: invalid syntax

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

$ python3
>>> for i in range(5):
    print(i)
  File "<stdin>", line 2
    print(i)
        ^
IndentationError: expected an indented block

А теперь посмотрим, что будет, если в первой строке цикла воспользоваться пробелами, а во второй — табуляцией:

$ python3
>>> for i in range(5):
        print(i) # здесь пробелы
        print(i**2) # здесь табуляция
    File "<stdin>", line 3
      print(i**2)
                ^
TabError: inconsistent use of tabs and spaces in indentation

NameError возникает при обращении к несуществующей переменной:

$ python3
>>> words = "Hello"
>>> word
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'word' is not defined

Ошибки в логике

Напишем простую программу на деление с остатком и сохраним как sample.py:

n = input()
m = input()
print(n % m)

и запустим её:

$ python3 sample.py
5
3
Traceback (most recent call last):
  File "sample.py", line 3, in <module>
    print(n % m)
TypeError: not all arguments converted during string formatting

Возникла ошибка TypeError, которая сообщает о неподходящем типе данных. Исправим программу:

n = int(input())
m = int(input())
print(n % m)

запустим на неподходящих данных:

$ python3 sample.py
xyz
Traceback (most recent call last):
  File "sample.py", line 1, in <module>
    n = int(input())
ValueError: invalid literal for int() with base 10: 'xyz'

Возникнет ValueError.
Эту ошибку ещё можно воспринимать как использование значения вне области допустимых значений (ОДЗ).

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

$ python3 sample.py
1
0
Traceback (most recent call last):
  File "sample.py", line 3, in <module>
    print(n % m)
ZeroDivisionError: integer division or modulo by zero

При работе с массивами нередко возникает ошибка IndexError. Она возникает при выходе за пределы массива:

$ python3
>>> L1 = [1, 2, 3]
>>> L1[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Что будет, если вызвать бесконечную рекурсию? Опишем её в программе endless.py

def noend():
    print("Hello!")
    noend()
noend()

Через некоторое время после запуска возникнет RecursionError:

Traceback (most recent call last):
  File "endless.py", line 4, in <module>
    noend()
  File "endless.py", line 3, in noend
    noend()
  File "endless.py", line 3, in noend
    noend()
  File "endless.py", line 3, in noend
    noend()
  [Previous line repeated 993 more times]
  File "endless.py", line 2, in noend
    print("Hello!")
RecursionError: maximum recursion depth exceeded while calling a Python object

Возможно, вам также будет интересно:

  • Index 10041 ticking block entity ошибка майнкрафт как решить
  • Index 0 size 0 ошибка zona
  • Index 0 is out of bounds for axis 0 with size 0 ошибка
  • Indesit стиральная машина ошибка замок
  • Indesit стиральная машина коды ошибок на светодиодах

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии