Except error as error nameerror name error is not defined

Исключения в Python, иерархия исключений в Python, обработка и генерация исключений, создание пользовательских исключений в Python

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

Исключения в языках программирования

Исключениями (exceptions) в языках программирования называют проблемы, возникающие в ходе выполнения программы, которые допускают возможность дальнейшей ее работы в рамках основного алгоритма. Типичным примером исключения является деление на ноль, невозможность считать данные из файла (устройства), отсутствие доступной памяти, доступ к закрытой области памяти и т.п. Для обработки таких ситуаций в языках программирования, как правило, предусматривается специальный механизм, который называется обработка исключений (exception handling).

Исключения разделяют на синхронные и асинхронные. Синхронные исключения могут возникнуть только в определенных местах программы. Например, если у вас есть код, который открывает файл и считывает из него данные, то исключение типа “ошибка чтения данных” может произойти только в указанном куске кода. Асинхронные исключения могут возникнуть в любой момент работы программы, они, как правило, связаны с какими-либо аппаратными проблемами, либо приходом данных. В качестве примера можно привести сигнал отключения питания.

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

Различают структурную и неструктурную обработку исключений. Неструктурная обработка предполагает регистрацию функции обработчика для каждого исключения, соответственно данная функция будет вызвана при возникновении конкретного исключения. Для структурной обработки язык программирования должен поддерживать специальные синтаксические конструкции, которые позволяют выделить код, который необходимо контролировать и код, который нужно выполнить при возникновении исключительной ситуации.

В Python выделяют два различных вида ошибок: синтаксические ошибки и исключения.

Синтаксические ошибки в Python

Синтаксические ошибки возникают в случае если программа написана с нарушениями требований Python к синтаксису. Определяются они в процессе парсинга программы. Ниже представлен пример с ошибочным написанием функции print.

>>> for i in range(10):
    prin("hello!")

Traceback (most recent call last):
  File "<pyshell#2>", line 2, in <module>
    prin("hello!")
NameError: name 'prin' is not defined

Исключения в Python

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

Пример исключения ZeroDivisionError, которое возникает при делении на 0.

>>> a = 10
>>> b = 0
>>> c = a / b
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    c = a / b
ZeroDivisionError: division by zero

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

Иерархия исключений в Python

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

BaseException
+– SystemExit
+– KeyboardInterrupt
+– GeneratorExit
+– Exception
     +– StopIteration
     +– StopAsyncIteration
     +– ArithmeticError
     |    +– FloatingPointError
     |    +– OverflowError
     |    +– ZeroDivisionError
     +– AssertionError
     +– AttributeError
     +– BufferError
     +– EOFError
     +– ImportError
          +– ModuleNotFoundError
     +– LookupError
     |    +– IndexError
     |    +– KeyError
     +– MemoryError
     +– NameError
     |    +– UnboundLocalError
     +– OSError
     |    +– BlockingIOError
     |    +– ChildProcessError
     |    +– ConnectionError
     |    |    +– BrokenPipeError
     |    |    +– ConnectionAbortedError
     |    |    +– ConnectionRefusedError
     |    |    +– ConnectionResetError
     |    +– FileExistsError
     |    +– FileNotFoundError
     |    +– InterruptedError
     |    +– IsADirectoryError
     |    +– NotADirectoryError
     |    +– PermissionError
     |    +– ProcessLookupError
     |    +– TimeoutError
     +– ReferenceError
     +– RuntimeError
     |    +– NotImplementedError
     |    +– RecursionError
     +– SyntaxError
     |    +– IndentationError
     |         +– TabError
     +– SystemError
     +– TypeError
     +– ValueError
     |    +– UnicodeError
     |         +– UnicodeDecodeError
     |         +– UnicodeEncodeError
     |         +– UnicodeTranslateError
     +– Warning
          +– DeprecationWarning
          +– PendingDeprecationWarning
          +– RuntimeWarning
          +– SyntaxWarning
          +– UserWarning
          +– FutureWarning
          +– ImportWarning
          +– UnicodeWarning
          +– BytesWarning
          +– ResourceWarning

Как видно из приведенной выше схемы, все исключения являются подклассом исключения BaseException. Более подробно об иерархии исключений и их описании можете прочитать здесь.

Обработка исключений в Python

Обработка исключений нужна для того, чтобы приложение не завершалось аварийно каждый раз, когда возникает исключение. Для этого блок кода, в котором возможно появление исключительной ситуации необходимо поместить во внутрь синтаксической конструкции try…except.

print("start")
try:
   val = int(input("input number: "))
   tmp = 10 / val
   print(tmp)
except Exception as e:
   print("Error! " + str(e))
print("stop")

В приведенной выше программе возможных два вида исключений – это ValueError, возникающее в случае, если на запрос программы “введите число”, вы введете строку, и ZeroDivisionError – если вы введете в качестве числа 0.

Вывод программы при вводе нулевого числа будет таким.

start input number: 0 Error! stop

Если бы инструкций try…except не было, то при выбросе любого из исключений программа аварийно завершится.

print("start")
val = int(input(“input number: “))
tmp = 10 / val
print(tmp)
print("stop")

Если ввести 0 на запрос приведенной выше программы, произойдет ее остановка с распечаткой сообщения об исключении.

start


input number: 0


Traceback (most recent call last):


 File “F:/work/programming/python/devpractice/tmp.py”, line 3, in <module>


   tmp = 10 / val


ZeroDivisionError: division by zero

Обратите внимание, надпись stop уже не печатается в конце вывода программы.

Согласно документу по языку Python, описывающему ошибки и исключения, оператор try работает следующим образом:

  • Вначале выполняется код, находящийся между операторами try и except.
  • Если в ходе его выполнения исключения не произошло, то код в блоке except пропускается, а код в блоке try выполняется весь до конца.
  • Если исключение происходит, то выполнение в рамках блока try прерывается и выполняется код в блоке except. При этом для оператора except можно указать, какие исключения можно обрабатывать в нем. При возникновении исключения, ищется именно тот блок except, который может обработать данное исключение.
  • Если среди except блоков нет подходящего для обработки исключения, то оно передается наружу из блока try. В случае, если обработчик исключения так и не будет найден, то исключение будет необработанным (unhandled exception) и программа аварийно остановится.

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

Если бы мы в нашей программе хотели обрабатывать только ValueError и ZeroDivisionError, то программа выглядела бы так.

print("start")
try:
   val = int(input("input number: "))
   tmp = 10 / val
   print(tmp)
except(ValueError, ZeroDivisionError):
   print("Error!")
print("stop")

Или так, если хотим обрабатывать ValueError, ZeroDivisionError по отдельность, и, при этом, сохранить работоспособность при возникновении исключений отличных от вышеперечисленных.

print("start")
try:
   val = int(input("input number: "))
   tmp = 10 / val
   print(tmp)
except ValueError:
   print("ValueError!")
except ZeroDivisionError:
   print("ZeroDivisionError!")
except:
   print("Error!")
print("stop")

Существует возможность передать подробную информацию о произошедшем исключении в код внутри блока except.

rint("start")
try:
   val = int(input("input number: "))
   tmp = 10 / val
   print(tmp)
except ValueError as ve:
   print("ValueError! {0}".format(ve))
except ZeroDivisionError as zde:
   print("ZeroDivisionError! {0}".format(zde))
except Exception as ex:
   print("Error! {0}".format(ex))
print("stop")

Использование finally в обработке исключений

Для выполнения определенного программного кода при выходе из блока try/except, используйте оператор finally.

try:
   val = int(input("input number: "))
   tmp = 10 / val
   print(tmp)
except:
   print("Exception")
finally:
  print("Finally code")

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

Если необходимо выполнить какой-то программный код, в случае если в процессе выполнения блока try не возникло исключений, то можно использовать оператор else.

try:
   f = open("tmp.txt", "r")
   for line in f:
       print(line)
   f.close()
except Exception as e:
   print(e)
else:
   print("File was readed")

Генерация исключений в Python

Для принудительной генерации исключения используется инструкция raise.

Самый простой пример работы с raise может выглядеть так.

try:
   raise Exception("Some exception")
except Exception as e:
   print("Exception exception " + str(e))

Таким образом, можно “вручную” вызывать исключения при необходимости.

Пользовательские исключения (User-defined Exceptions) в Python

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

Для реализации собственного типа исключения необходимо создать класс, являющийся наследником от одного из классов исключений.

class NegValException(Exception):
   pass

try:
   val = int(input("input positive number: "))
   if val < 0:
       raise NegValException("Neg val: " + str(val))
   print(val + 10)
except NegValException as e:
  print(e)

P.S.

Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
Книга: Pandas. Работа с данными

<<< Python. Урок 10. Функции в Python   Python. Урок 12. Ввод-вывод данных. Работа с файлами>>>

Содержание

Введение
Пример с базовым Exception
Два исключения
except Error as e:: Печать текста ошибки
else
finally
raise
Пример 2
Пример 3
Исключения, которые не нужно обрабатывать
Список исключений
Разбор примеров: IndexError, ValueError, KeyError
Похожие статьи

Введение

Если в коде есть ошибка, которую видит интерпретатор поднимается исключение, создается так называемый
Exception Object, выполнение останавливается, в терминале
показывается Traceback.

В английском языке используется словосочетание Raise Exception

Исключение, которое не было предусмотрено разработчиком называется необработанным (Unhandled Exception)

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

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

Исключение, которое предусмотрено в коде называется обработанным (Handled)

Блок try except имеет следующий синтаксис

try:
pass
except Exception:
pass
else:
pass
finally:
pass

В этой статье я создал файл

try_except.py

куда копирую код из примеров.

Пример

Попробуем открыть несуществующий файл и воспользоваться базовым Exception

try:
f = open(‘missing.txt’)
except Exception:
print(‘ERR: File not found’)

python try_except.py

ERR: No missing.txt file found

Ошибка поймана, видно наше сообщение а не Traceback

Проверим, что когда файл существует всё хорошо

try:
f = open(‘existing.txt’)
except Exception:
print(‘ERR: File not found’)

python try_except.py

Пустота означает успех

Два исключения

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

try:
f = open(‘existing.txt’)
x = bad_value
except Exception:
print(‘ERR: File not found’)

python try_except.py

ERR: File not found

Файл открылся, но так как в следующей строке ошибка — в терминале появилось вводящее в заблуждение сообщение.
Проблема не в том, что «File not found» а в том, что bad_value нигде не определёно.

Избежать сбивающих с толку сообщений можно указав тип ожидаемой ошибки. В данном примере это FileNotFoundError

try:
# expected exception
f = open(‘existing.txt’)
# unexpected exception should result in Traceback
x = bad_value
except FileNotFoundError:
print(‘ERR: File not found’)

python try_except.py

Traceback (most recent call last):
File «/home/andrei/python/try_except2.py», line 5, in <module>
x = bad_value
NameError: name ‘bad_value’ is not defined

Вторая ошибка не поймана поэтому показан Traceback

Поймать обе ошибки можно добавив второй Exception

try:
# expected exception should be caught by FileNotFoundError
f = open(‘missing.txt’)
# unexpected exception should be caught by Exception
x = bad_value
except FileNotFoundError:
print(‘ERR: File not found’)
except Exception:
print(‘ERR: Something unexpected went wrong’)

python try_except.py

ERR: File not found

ERR: Something unexpected went wrong

Печать текста ошибки

Вместо своего текста можно выводить текст ошибки. Попробуем с существующим файлом — должна быть одна пойманная ошибка.

try:
# expected exception should be caught by FileNotFoundError
f = open(‘existing.txt’)
# unexpected exception should be caught by Exception
x = bad_value
except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)

python try_except.py

name ‘bad_value’ is not defined

Теперь попытаемся открыть несуществующий файл — должно быть две пойманные ошибки.

try:
# expected exception should be caught by FileNotFoundError
f = open(‘missing.txt’)
# unexpected exception should be caught by Exception
x = bad_value
except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)

python try_except.py

name ‘bad_value’ is not defined

[Errno 2] No such file or directory: ‘missing.txt’

else

Блок else будет выполнен если исключений не будет поймано.

Попробуем открыть существующий файл

existing.txt

в котором есть строка

www.heihei.ru

try:
f = open(‘existing.txt’)
except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
else:
print(f.read())
f.close()

python try_except.py

www.heihei.ru

Если попробовать открыть несуществующий файл

missing.txt

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

[Errno 2] No such file or directory: ‘missing.txt’

finally

Блок finally будет выполнен независимо от того, поймано исключение или нет

try:
f = open(‘existing.txt’)
except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
else:
print(f.read())
f.close()
finally:
print(«Finally!»)

www.heihei.ru

Finally!

А если попытаться открыть несуществующий

missing.txt

[Errno 2] No such file or directory: ‘missing.txt’
Finally!

Когда нужно применять finally:

Рассмотрим скрипт, который вносит какие-то изменения в систему.
Затем он пытается что-то сделать. В конце возвращает
систему в исходное состояние.

Если ошибка случится в середине скрипта — он уже не сможет вернуть систему в исходное состояние.

Но если вынести возврат к исходному состоянию в блок finally он сработает даже при ошибке
в предыдущем блоке.

import os

def make_at(path, dir_name):
original_path = os.getcwd()
os.chdir(path)
os.mkdir(dir_name)
os.chdir(original_path)

Этот скрипт не вернётся в исходную директорию при ошибке в os.mkdir(dir_name)

А у скрипта ниже такой проблемы нет

def make_at(path, dir_name):
original_path = os.getcwd()
os.chdir(path)
try:
os.mkdir(dir_name)
finally:
os.chdir(original_path)

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

import os
import sys

def make_at(path, dir_name):
original_path = os.getcwd()
os.chdir(path)
try:
os.mkdir(dir_name)

except OSError as e:
print(e, file=sys.stderr)
raise
finally:
os.chdir(original_path)

По умолчанию print() выводит в sys.stdout, но в случае ислючений логичнее выводить в sys.stderr

raise

Можно вызывать исключения вручную в любом месте кода с помощью
raise.

try:
f = open(‘outdated.txt’)
if f.name == ‘outdated.txt’:
raise Exception
except FileNotFoundError as e:
print(e)
except Exception as e:
print(‘File is outdated!’)
else:
print(f.read())
f.close()
finally:
print(«Finally!»)

python try_except.py

File is outdated!
Finally!

raise

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

Для этого достаточно вызвать raise без аргументов — поднимется текущее исключение.

Пример 2

Рассмотрим функцию, которая принимает числа прописью и возвращает цифрами

DIGIT_MAP = {
‘zero’: ‘0’,
‘one’: ‘1’,
‘two’: ‘2’,
‘three’: ‘3’,
‘four’: ‘4’,
‘five’: ‘5’,
‘six’: ‘6’,
‘seven’: ‘7’,
‘eight’: ‘8’,
‘nine’: ‘9’,
}

def convert(s):
number = »
for token in s:
number += DIGIT_MAP[token]
x = int(number)
return x

python

>>> from exc1 import convert
>>> convert(«one three three seven».split())
1337

Теперь передадим аргумент, который не предусмотрен в словаре

>>> convert(«something unseen«.split())
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
File «/home/andrei/python/exc1.py», line 17, in convert
number &plu= DIGIT_MAP[token]
KeyError: ‘something’

KeyError — это тип Exception объекта. Полный список можно изучить в конце статьи.

Исключение прошло следующий путь:

REPL convert() DIGIT_MAP(«something») KeyError

Обработать это исключение можно внеся изменения в функцию convert

convert(s):
try:
number = »
for token in s:
number += DIGIT_MAP[token]
x = int(number)
print(«Conversion succeeded! x = «, x)
except KeyError:
print(«Conversion failed!»)
x = —1
return x

>>> from exc1 import convert
>>> convert(«one nine six one».split())
Conversion succeeded! x = 1961
1961
>>> convert(«something unseen».split())
Conversion failed!
-1

Эта обработка не спасает если передать int вместо итерируемого объекта

>>> convert(2022)
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
File «/home/andrei/python/exc1.py», line 17, in convert
for token in s:
TypeError: ‘int’ object is not iterable

Нужно добавить обработку TypeError


except KeyError:
print(«Conversion failed!»)
x = —1
except TypeError:
print(«Conversion failed!»)
x = —1
return x

>>> from exc1 import convert
>>> convert(«2022».split())
Conversion failed!
-1

Избавимся от повторов, удалив принты, объединив два исключения в кортеж и вынесем присваивание значения x
из try блока.

Также добавим

докстринг

с описанием функции.

def convert(s):
«»»Convert a string to an integer.»»»
x = —1
try:
number = »
for token in s:
number += DIGIT_MAP[token]
x = int(number)
except (KeyError, TypeError):
pass
return x

>>> from exc4 import convert
>>> convert(«one nine six one».split())
1961
>>> convert(«bad nine six one».split())
-1
>>> convert(2022)
-1

Ошибки обрабатываются, но без принтов, процесс не очень информативен.

Грамотно показать текст сообщений об ошибках можно импортировав sys и изменив функцию

import sys

DIGIT_MAP = {
‘zero’: ‘0’,
‘one’: ‘1’,
‘two’: ‘2’,
‘three’: ‘3’,
‘four’: ‘4’,
‘five’: ‘5’,
‘six’: ‘6’,
‘seven’: ‘7’,
‘eight’: ‘8’,
‘nine’: ‘9’,
}

def convert(s):
«»»Convert a string to an integer.»»»
try:
number = »
for token in s:
number += DIGIT_MAP[token]
return(int(number))
except (KeyError, TypeError) as e:
print(f«Conversion error: {e!r}», file=sys.stderr)
return1

>>> from exc1 import convert
>>> convert(2022)
Conversion error: TypeError(«‘int’ object is not iterable»)
-1
>>> convert(«one nine six one».split())
1961
>>> convert(«bad nine six one».split())
Conversion error: KeyError(‘bad’)

Ошибки обрабатываются и их текст виден в терминале.

С помощью

!r

выводится

repr()

ошибки

raise вместо кода ошибки

В предыдущем примере мы полагались на возвращение числа -1 в качестве кода ошибки.

Добавим к коду примера функцию string_log() и поработаем с ней

def string_log(s):
v = convert(s)
return log(v)

>>> from exc1 import string_log
>>> string_log(«one two eight».split())
4.852030263919617
>>> string_log(«bad one two».split())
Conversion error: KeyError(‘bad’)
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
File «/home/andrei/exc1.py», line 32, in string_log
return log(v)
ValueError: math domain error

convert() вернул -1 а string_log попробовал его обработать и не смог.

Можно заменить return -1 на raise. Это считается более правильным подходом в Python

def convert(s):
«»»Convert a string to an integer.»»»
try:
number = »
for token in s:
number += DIGIT_MAP[token]
return(int(number))
except (KeyError, TypeError) as e:
print(f«Conversion error: {e!r}», file=sys.stderr)
raise

>>> from exc7 import string_log
>>> string_log(«one zero».split())
2.302585092994046
>>> string_log(«bad one two».split())
Conversion error: KeyError(‘bad’)
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
File «/home/andrei/exc7.py», line 31, in string_log
v = convert(s)
File «/home/andrei/exc7.py», line 23, in convert
number += DIGIT_MAP[token]
KeyError: ‘bad’

Пример 3

Рассмотрим алгоритм по поиску квадратного корня

def sqrt(x):
«»»Compute square roots using the method
of Heron of Alexandria.

Args:
x: The number for which the square root
is to be computed.

Returns:
The square root of x.
«»»

guess = x
i = 0
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
return guess

def main():
print(sqrt(9))
print(sqrt(2))

if __name__ == ‘__main__’:
main()

python sqrt_ex.py

3.0
1.414213562373095

При попытке вычислить корень от -1 получим ошибку

def main():
print(sqrt(9))
print(sqrt(2))
print(sqrt(-1))

python sqrt_ex.py

3.0
1.414213562373095
Traceback (most recent call last):
File «/home/andrei/sqrt_ex.py», line 26, in <module>
main()
File «/home/andrei/sqrt_ex.py», line 23, in main
print(sqrt(-1))
File «/home/andrei/sqrt_ex.py», line 16, in sqrt
guess = (guess + x / guess) / 2.0
ZeroDivisionError: float division by zero

В строке

guess = (guess + x / guess) / 2.0

Происходит деление на ноль

Обработать можно следующим образом:

def main():
try:
print(sqrt(9))
print(sqrt(2))
print(sqrt(-1))
except ZeroDivisionError:
print(«Cannot compute square root «
«of a negative number.»)

print(«Program execution continues «
«normally here.»)

Обратите внимание на то, что в try помещены все вызовы функции

python sqrt_ex.py

3.0
1.414213562373095
Cannot compute square root of a negative number.
Program execution continues normally here.

Если пытаться делить на ноль несколько раз — поднимется одно исключение и всё что находится в блоке
try после выполняться не будет

def main():
try:
print(sqrt(9))
print(sqrt(-1))
print(sqrt(2))
print(sqrt(-1))

python sqrt_ex.py

3.0
Cannot compute square root of a negative number.
Program execution continues normally here.

Каждую попытку вычислить корень из -1 придётся обрабатывать отдельно. Это кажется неудобным, но
в этом и заключается смысл — каждое место где вы ждёте ислючение нужно помещать в свой
try except блок.

Можно обработать исключение так:

try:
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
except ZeroDivisionError:
raise ValueError()
return guess

def main():
print(sqrt(9))
print(sqrt(-1))

python sqrt_ex.py

3.0
Traceback (most recent call last):
File «/home/andrei/sqrt_ex3.py», line 17, in sqrt
guess = (guess + x / guess) / 2.0
ZeroDivisionError: float division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «/home/andrei/sqrt_ex3.py», line 30, in <module>
main()
File «/home/andrei/sqrt_ex3.py», line 25, in main
print(sqrt(-1))
File «/home/andrei/sqrt_ex3.py», line 20, in sqrt
raise ValueError()
ValueError

Гораздо логичнее поднимать исключение сразу при получении аргумента

def sqrt(x):
«»»Compute square roots using the method
of Heron of Alexandria.

Args:
x: The number for which the square root
is to be computed.

Returns:
The square root of x.

Raises:
ValueError: If x is negative
«»»

if x < 0:
raise ValueError(
«Cannot compute square root of «
f«negative number {x}»)

guess = x
i = 0
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
return guess

def main():
print(sqrt(9))
print(sqrt(-1))
print(sqrt(2))
print(sqrt(-1))

if __name__ == ‘__main__’:
main()

python sqrt_ex.py

3.0
Traceback (most recent call last):
File «/home/avorotyn/python/lessons/pluralsight/core_python_getting_started/chapter8/sqrt_ex4.py», line 35, in <module>
main()
File «/home/avorotyn/python/lessons/pluralsight/core_python_getting_started/chapter8/sqrt_ex4.py», line 30, in main
print(sqrt(-1))
File «/home/avorotyn/python/lessons/pluralsight/core_python_getting_started/chapter8/sqrt_ex4.py», line 17, in sqrt
raise ValueError(
ValueError: Cannot compute square root of negative number -1

Пока получилось не очень — виден Traceback

Убрать Traceback можно добавив обработку ValueError в вызов функций

import sys

def sqrt(x):
«»»Compute square roots using the method
of Heron of Alexandria.

Args:
x: The number for which the square root
is to be computed.

Returns:
The square root of x.

Raises:
ValueError: If x is negative
«»»

if x < 0:
raise ValueError(
«Cannot compute square root of «
f«negative number {x}»)

guess = x
i = 0
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
return guess

def main():
try:
print(sqrt(9))
print(sqrt(2))
print(sqrt(-1))
print(«This is never printed»)
except ValueError as e:
print(e, file=sys.stderr)

print(«Program execution continues normally here.»)

if __name__ == ‘__main__’:
main()

python sqrt_ex.py

3.0
1.414213562373095
Cannot compute square root of negative number -1
Program execution continues normally here.

Исключения, которые не нужно обрабатывать

IndentationError, SyntaxError, NameError нужно исправлять в коде а не пытаться обработать.

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

Список исключений

Список встроенных в Python исключений

Существуют следующие типы объектов Exception

BaseException
+— SystemExit
+— KeyboardInterrupt
+— GeneratorExit
+— Exception
+— StopIteration
+— StopAsyncIteration
+— ArithmeticError
| +— FloatingPointError
| +— OverflowError
| +— ZeroDivisionError
+— AssertionError
+— AttributeError
+— BufferError
+— EOFError
+— ImportError
| +— ModuleNotFoundError
+— LookupError
| +— IndexError
| +— KeyError
+— MemoryError
+— NameError
| +— UnboundLocalError
+— OSError
| +— BlockingIOError
| +— ChildProcessError
| +— ConnectionError
| | +— BrokenPipeError
| | +— ConnectionAbortedError
| | +— ConnectionRefusedError
| | +— ConnectionResetError
| +— FileExistsError
| +— FileNotFoundError
| +— InterruptedError
| +— IsADirectoryError
| +— NotADirectoryError
| +— PermissionError
| +— ProcessLookupError
| +— TimeoutError
+— ReferenceError
+— RuntimeError
| +— NotImplementedError
| +— RecursionError
+— SyntaxError
| +— IndentationError
| +— TabError
+— SystemError
+— TypeError
+— ValueError
| +— UnicodeError
| +— UnicodeDecodeError
| +— UnicodeEncodeError
| +— UnicodeTranslateError
+— Warning
+— DeprecationWarning
+— PendingDeprecationWarning
+— RuntimeWarning
+— SyntaxWarning
+— UserWarning
+— FutureWarning
+— ImportWarning
+— UnicodeWarning
+— BytesWarning
+— EncodingWarning
+— ResourceWarning

IndexError

Объекты, которые поддерживают

протокол

Sequence должны поднимать исключение IndexError при использовании несуществующего индекса.

IndexError как и

KeyError

относится к ошибкам поиска LookupError

Пример

>>> a = [0, 1, 2]
>>> a[3]

Traceback (most recent call last):
File «<stdin>», line 1, in <module>
IndexError: list index out of range

ValueError

ValueError поднимается когда объект правильного типа, но содержит неправильное значение

>>> int(«text»)

Traceback (most recent call last):
File «<stdin>», line 1, in <module>
ValueError: invalid literal for int() with base 10: ‘text’

KeyError

KeyError поднимается когда поиск по ключам не даёт результата

>>> sites = dict(urn=1, heihei=2, eth1=3)
>>> sites[«topbicycle»]

Traceback (most recent call last):
File «<stdin>», line 1, in <module>
KeyError: ‘topbicycle’

TypeError

TypeError поднимается когда для успешного выполнения операции нужен объект
определённого типа, а предоставлен другой тип.

pi = 3.1415

text = «Pi is approximately « + pi

python str_ex.py

Traceback (most recent call last):
File «str_ex.py», line 3, in <module>
text = «Pi is approximately » + pi
TypeError: can only concatenate str (not «float») to str

Пример из статьи

str()

SyntaxError

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

Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type «help», «copyright», «credits» or «license» for more information.
>>>
>>>
>>> 0 <> 0
File «<stdin>», line 1
0 <> 0
^
SyntaxError: invalid syntax

Пример из статьи

__future__

Похожие статьи

Python
Интерактивный режим
str: строки
: перенос строки
Списки []
if, elif, else
Циклы
Функции
Пакеты
*args **kwargs
ООП
enum
Опеределить тип переменной Python
Тестирование с помощью Python
Работа с REST API на Python
Файлы: записать, прочитать, дописать, контекстный менеджер…
Скачать файл по сети
SQLite3: работа с БД
datetime: Дата и время в Python
json.dumps
Selenium + Python
Сложности при работе с Python
DJANGO
Flask
Скрипт для ZPL принтера
socket :Python Sockets
Виртуальное окружение
subprocess: выполнение bash команд из Python
multiprocessing: несколько процессов одновременно
psutil: cистемные ресурсы
sys.argv: аргументы командной строки
PyCharm: IDE
pydantic: валидация данных
paramiko: SSH из Python
enumerate
logging: запись в лог
Обучение программированию на Python

You execute your Python program and you see an error, “NameError: name … is not defined”. What does it mean?

In this article I will explain you what this error is and how you can quickly fix it.

What causes a Python NameError?

The Python NameError occurs when Python cannot recognise a name in your program. A name can be either related to a built-in function or to something you define in your program (e.g. a variable or a function).

Let’s have a look at some examples of this error, to do that I will create a simple program and I will show you common ways in which this error occurs during the development of a Python program.

Ready?

A Simple Program to Print the Fibonacci Sequence

We will go through the creation of a program that prints the Fibonacci sequence and while doing that we will see 4 different ways in which the Python NameError can appear.

First of all, to understand the program we are creating let’s quickly introduce the Fibonacci sequence.

In the Fibonacci sequence every number is the sum of the two preceding numbers in the sequence. The sequence starts with 0 and 1.

Below you can see the first 10 numbers in the sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

That’s pretty much everything we need to know to create a Python program that generates this sequence.

Let’s get started!

To simplify things our Python program will print the sequence starting from the number 1.

Here is the meaning of the variables n1, n2 and n:

Variable Meaning
n nth term of the sequence
n1 (n-1)th term of the sequence
n2 (n-2)th term of the sequence

And here is our program.

At each iteration of the while loop we:

  • Calculate the nth term as the sum of the (n-2)th and (n-1)th terms.
  • Assign the value of the (n-1)th terms to the (n-2)th terms.
  • Assign the value of the nth terms to the (n-1)th terms.

We assign the values to the (n-2)th and (n-1)th terms so we can use them in the next iteration of the while loop to calculate the value of the nth term.

number_of_terms = int(input("How many terms do you want for the sequence? "))
n1 = 1
n2 = 0

while count < number_of_terms:
    n = n1 + n2
    print(n)
    n2 = n1
    n1 = n
    count += 1

I run the program, and….

How many terms do you want for the sequence? 5
Traceback (most recent call last):
  File "fibonacci.py", line 5, in <module>
    while count < number_of_terms:
NameError: name 'count' is not defined

What happened?

This syntax error is telling us that the name count is not defined.

It basically means that the count variable is not defined.

So in this specific case we are using the variable count in the condition of the while loop without declaring it before. And because of that Python generates this error.

Let’s define count at the beginning of our program and try again.

number_of_terms = int(input("How many terms do you want for the sequence? "))
count = 0
n1 = 1
n2 = 0
.....
....
...

And if we run the program, we get…

How many terms do you want for the sequence? 5
1
2
3
5
8

So, all good.

Lesson 1: The Python NameError happens if you use a variable without declaring it.

Order Really Counts in a Python Program

Now I want to create a separate function that calculates the value of the nth term of the sequence.

In this way we can simply call that function inside the while loop.

In this case our function is very simple, but this is just an example to show you how we can extract part of our code into a function.

This makes our code easier to read (imagine if the calculate_nth_term function was 50 lines long):

number_of_terms = int(input("How many terms do you want for the sequence? "))
count = 0
n1 = 1
n2 = 0

while count < number_of_terms:
    n = calculate_nth_term(n1, n2)
    print(n)
    n2 = n1
    n1 = n
    count += 1

def calculate_nth_term(n1, n2):
    n = n1 + n2
    return n

And here is the output of the program…

How many terms do you want for the sequence? 5
Traceback (most recent call last):
  File "fibonacci.py", line 7, in <module>
    n = calculate_nth_term(n1, n2)
NameError: name 'calculate_nth_term' is not defined

Wait…a NameError again!?!

We have defined the function we are calling so why the error?

Because we are calling the function calculate_nth_term before defining that same function.

We need to make sure the function is defined before being used.

So, let’s move the function before the line in which we call it and see what happens:

number_of_terms = int(input("How many terms do you want for the sequence? "))
count = 0
n1 = 1
n2 = 0

def calculate_nth_term(n1, n2):
    n = n1 + n2
    return n

while count < number_of_terms:
    n = calculate_nth_term(n1, n2)
    print(n)
    n2 = n1
    n1 = n
    count += 1
How many terms do you want for the sequence? 4
1
2
3
5

Our program works well this time!

Lesson 2: Make sure a variable or function is declared before being used in your code (and not after).

Name Error With Built-in Functions

I want to improve our program and stop its execution if the user provides an input that is not a number.

With the current version of the program this is what happens if something that is not a number is passed as input:

How many terms do you want for the sequence? not_a_number
Traceback (most recent call last):
  File "fibonacci.py", line 1, in <module>
    number_of_terms = int(input("How many terms do you want for the sequence? "))
ValueError: invalid literal for int() with base 10: 'not_a_number'

That’s not a great way to handle errors.

A user of our program wouldn’t know what to do with this error…

We want to exit the program with a clear message for our user if something different that a number is passed as input to the program.

To stop the execution of our program we can use the exit() function that belongs to the Python sys module.

The exit function takes an optional argument, an integer that represents the exit status status of the program (the default is zero).

Let’s handle the exception thrown when we don’t pass a number to our program. We will do it with the try except statement

try:
    number_of_terms = int(input("How many terms do you want for the sequence? "))
except ValueError:
    print("Unable to continue. Please provide a valid number.")
    sys.exit(1)

Let’s run it!

How many terms do you want for the sequence? not_a_number
Unable to continue. Please provide a valid number.
Traceback (most recent call last):
  File "fibonacci.py", line 2, in <module>
    number_of_terms = int(input("How many terms do you want for the sequence? "))
ValueError: invalid literal for int() with base 10: 'not_a_number'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "fibonacci.py", line 5, in <module>
    sys.exit(1)
NameError: name 'sys' is not defined

Bad news, at the end you can see another NameError…it says that sys is not defined.

That’s because I have used the exit() function of the sys module without importing the sys module at the beginning of my program. Let’s do that.

Here is the final program:

import sys
  
try:
    number_of_terms = int(input("How many terms do you want for the sequence? "))
except ValueError:
    print("Unable to continue. Please provide a valid number.")
    sys.exit(1)

count = 0
n1 = 1
n2 = 0

def calculate_nth_term(n1, n2):
    n = n1 + n2
    return n

while count < number_of_terms:
    n = calculate_nth_term(n1, n2)
    print(n)
    n2 = n1
    n1 = n
    count += 1

And when I run it I can see that the exception is handled correctly:

How many terms do you want for the sequence? not_a_number
Unable to continue. Please provide a valid number.

Lesson 3: Remember to import any modules that you use in your Python program.

Catch Any Misspellings

The NameError can also happen if you misspell something in your program.

For instance, let’s say when I call the function to calculate the nth term of the Fibonacci sequence I write the following:

n = calculate_nt_term(n1, n2)

As you can see, I missed the ‘h’ in ‘nth’:

How many terms do you want for the sequence? 5
Traceback (most recent call last):
  File "fibonacci.py", line 18, in <module>
    n = calculate_nt_term(n1, n2)
NameError: name 'calculate_nt_term' is not defined

Python cannot find the name “calculate_nt_term” in the program because of the misspelling.

This can be harder to find if you have written a very long program.

Lesson 4: Verify that there are no misspellings in your program when you define or use a variable or a function. This also applies to Python built-in functions.

Conclusion

You now have a guide to understand why the error “NameError: name … is not defined” is raised by Python during the execution of your programs.

Let’s recap the scenarios I have explained:

  • The Python NameError happens if you use a variable without declaring it.
  • Make sure a variable or function is declared before being used in your code (and not after).
  • Remember to import any modules that you use in your Python program.
  • Verify that there are no misspellings in your program when you define or use a variable or a function. This also applies to Python built-in functions.

Does it make sense?

If you have any questions feel free to post them in the comments below 🙂

I have put together for you the code we have created in this tutorial, you can get it here.

And if you are just getting started with Python have a look at this free checklist I created to build your Python knowledge.

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Until now error messages haven’t been more than mentioned, but if you have tried
out the examples you have probably seen some. There are (at least) two
distinguishable kinds of errors: syntax errors and exceptions.

8.1. Syntax Errors¶

Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:

>>> while True print 'Hello world'
  File "<stdin>", line 1, in ?
    while True print 'Hello world'
                   ^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at
the earliest point in the line where the error was detected. The error is
caused by (or at least detected at) the token preceding the arrow: in the
example, the error is detected at the keyword print, since a colon
(‘:’) is missing before it. File name and line number are printed so you
know where to look in case the input came from a script.

8.2. Exceptions¶

Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called exceptions and are not unconditionally fatal: you will soon learn
how to handle them in Python programs. Most exceptions are not handled by
programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in
the example are ZeroDivisionError, NameError and TypeError.
The string printed as the exception type is the name of the built-in exception
that occurred. This is true for all built-in exceptions, but need not be true
for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what
caused it.

The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions¶

It is possible to write programs that handle selected exceptions. Look at the
following example, which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using Control-C or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the KeyboardInterrupt exception.

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."
...

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and
    except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the
    try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the
    clause is skipped. Then if its type matches the exception named after the
    except keyword, the except clause is executed, and then execution
    continues after the try statement.
  • If an exception occurs which does not match the exception named in the except
    clause, it is passed on to outer try statements; if no handler is
    found, it is an unhandled exception and execution stops with a message as
    shown above.

A try statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
in other handlers of the same try statement. An except clause may
name multiple exceptions as a parenthesized tuple, for example:

... except (RuntimeError, TypeError, NameError):
...     pass

The last except clause may omit the exception name(s), to serve as a wildcard.
Use this with extreme caution, since it is easy to mask a real programming error
in this way! It can also be used to print an error message and then re-raise
the exception (allowing a caller to handle the exception as well):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

The tryexcept statement has an optional else
clause
, which, when present, must follow all except clauses. It is useful for
code that must be executed if the try clause does not raise an exception. For
example:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

The use of the else clause is better than adding additional code to
the try clause because it avoids accidentally catching an exception
that wasn’t raised by the code being protected by the try
except statement.

When an exception occurs, it may have an associated value, also known as the
exception’s argument. The presence and type of the argument depend on the
exception type.

The except clause may specify a variable after the exception name (or tuple).
The variable is bound to an exception instance with the arguments stored in
instance.args. For convenience, the exception instance defines
__str__() so the arguments can be printed directly without having to
reference .args.

One may also instantiate an exception first before raising it and add any
attributes to it as desired.

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

If an exception has an argument, it is printed as the last part (‘detail’) of
the message for unhandled exceptions.

Exception handlers don’t just handle exceptions if they occur immediately in the
try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example:

>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as detail:
...     print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero

8.4. Raising Exceptions¶

The raise statement allows the programmer to force a specified
exception to occur. For example:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: HiThere

The sole argument to raise indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from Exception).

If you need to determine whether an exception was raised but don’t intend to
handle it, a simpler form of the raise statement allows you to
re-raise the exception:

>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print 'An exception flew by!'
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

8.5. User-defined Exceptions¶

Programs may name their own exceptions by creating a new exception class (see
Classes for more about Python classes). Exceptions should typically
be derived from the Exception class, either directly or indirectly. For
example:

>>> class MyError(Exception):
...     def __init__(self, value):
...         self.value = value
...     def __str__(self):
...         return repr(self.value)
...
>>> try:
...     raise MyError(2*2)
... except MyError as e:
...     print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

In this example, the default __init__() of Exception has been
overridden. The new behavior simply creates the value attribute. This
replaces the default behavior of creating the args attribute.

Exception classes can be defined which do anything any other class can do, but
are usually kept simple, often only offering a number of attributes that allow
information about the error to be extracted by handlers for the exception. When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expr -- input expression in which the error occurred
        msg  -- explanation of the error
    """

    def __init__(self, expr, msg):
        self.expr = expr
        self.msg = msg

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        prev -- state at beginning of transition
        next -- attempted new state
        msg  -- explanation of why the specific transition is not allowed
    """

    def __init__(self, prev, next, msg):
        self.prev = prev
        self.next = next
        self.msg = msg

Most exceptions are defined with names that end in “Error,” similar to the
naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may
occur in functions they define. More information on classes is presented in
chapter Classes.

8.6. Defining Clean-up Actions¶

The try statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances. For
example:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print 'Goodbye, world!'
...
Goodbye, world!
KeyboardInterrupt

A finally clause is always executed before leaving the try
statement, whether an exception has occurred or not. When an exception has
occurred in the try clause and has not been handled by an
except clause (or it has occurred in a except or
else clause), it is re-raised after the finally clause has
been executed. The finally clause is also executed “on the way out”
when any other clause of the try statement is left via a
break, continue or return statement. A more
complicated example (having except and finally clauses in
the same try statement works as of Python 2.5):

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print "division by zero!"
...     else:
...         print "result is", result
...     finally:
...         print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the finally clause is executed in any event. The
TypeError raised by dividing two strings is not handled by the
except clause and therefore re-raised after the finally
clause has been executed.

In real world applications, the finally clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.

8.7. Predefined Clean-up Actions¶

Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen.

for line in open("myfile.txt"):
    print line

The problem with this code is that it leaves the file open for an indeterminate
amount of time after the code has finished executing. This is not an issue in
simple scripts, but can be a problem for larger applications. The
with statement allows objects like files to be used in a way that
ensures they are always cleaned up promptly and correctly.

with open("myfile.txt") as f:
    for line in f:
        print line

After the statement is executed, the file f is always closed, even if a
problem was encountered while processing the lines. Other objects which provide
predefined clean-up actions will indicate this in their documentation.

Python NameError

Introduction to Python NameError

The following article provides an outline for Python NameError. NameError is a kind of error in python that occurs when executing a function, variable, library or string without quotes that have been typed in the code without any previous Declaration. When the interpreter, upon execution, cannot identify the global or a local name, it throws a NameError. It can be viewed in the last line of the error message to understand the NameError where the function, variable, package or string that has not been declared will be shown in the message saying the respective function, package, variable “is not defined”.

Syntax of Python NameError

When writing a function with a name, we often miss to call the exact function name in the future, which will lead to a NameError.

Example:

Code:

## Functions which return values
def calc_sum(x,y):
    op = x + y
    return(op)

ss = calc_sum(5,10)
print(ss)

Output:

Python NameError 1

For the same function, let’s see the NameError.

Code:

## Functions which return values
def calc_sum(x,y):
    op = x + y
    return(op)

ss = calc_su(5,10)
print(ss)

Output:

Python NameError 2

It was originally written to perform some operation between two numbers and named as calc_sum, but upon calling it, we used the name calc_su, so it is not defined previously, and it will throw us a NameError.

How NameError Works?

When working with user-defined variables in coding, the NameError often occurs due to the difficulty in identifying the local/global values for the interpreter.

Example:

Code:

l1 = [1,2,5,8,9]
l2 = [1,5.6,"hello"] # mix of data types
l1[1] = 100 # muting the 1st position of l1 to 100
print(l1)
del l1[2] # delete from a position 2
print(l1)

Output:

Python NameError 3

Code:

l1 = [1,2,5,8,9]
l2 = [1,5.6,"hello"] # mix of data types
l1[1] = 100 # muting the 1st position of l1 to 100
print(l1)
del l[2] # delete from a position 2

Here we are performing a delete operation on a variable l that is not defined.

Only l1 & l2 have been defined, and the interpreter can only identify l1 & l2 variables. So if we operate on l, which is not defined, it will throw us a NameError.

Output:

Python NameError 4

There are cases of NameError that also occurs during operations done with a python library or a package. Where if we miss to import the package or library or if we haven’t defined the name of that package or library and upon executing an operation using that library, we will get a NameError

Example:

Code:

l10 = [1,2,6,7,4,5,7,8,6,3]
l11 = [1,2,6,7,4,5,7,8,6,3,1000]
## numpy operations
np.mean(l11)
np.median(l11)
np.std(l11)

Output:

Python NameError 5

We haven’t imported the numpy library as np, and upon executing the operation, we will see the NameError.

Code:

import numpy as np
l10 = [1,2,6,7,4,5,7,8,6,3]
l11 = [1,2,6,7,4,5,7,8,6,3,1000]
## numpy operations
print(np.mean(l11))
print(np.median(l11))
print(np.std(l11))

Output:

Python NameError 6

Another kind of NameError occurs when we fail to insert a string value inside the quotes, and the interpreter identifies it as a variable and throws a NameError.

Example:

Code:

print('Its a Beautiful day')
name=('Bala')
print(name,'Its a Beautiful day')

Output:

Python NameError 7

Code:

Error,
print('Its a Beautiful day')
name=(Bala)
print(name,'Its a Beautiful day')

Here we fail to put the string inside the quotes, so the console will throw us the NameError.

Output:

fail to put the string inside the quotes

Avoiding NameErrors in Python

The NameError can be avoided easily by using the Python Error handling technique or exception handling, which denotes the user about the NameError that is occurring in the block of code without actually throwing an error.

The most common errors that occur in python is the SyntaxError & NameError. When we write our code and if the programming language does not accept it, then arises the SyntaxError. SyntaxError can be corrected by following the programming language guidelines in a way the interpreter could understand. The NameError can be avoided by using a technique called Exception Handling.

Code:

def my_func():
    x="Name Error Exception"
    print(y)
my_func()   

Output:

Python NameError 9

Even if we write code without any SyntaxError, the program can result in runtime errors. These are called Exceptions. There are numerous built-in exceptions available in Python, and One such exception is NameError Exception.

In Python, the NameError exception comes into the picture when we try to use or refer to a name that is not defined locally or globally.

Example:

For NameError Exception handling.

Code:

try:
    x="Name Error Exception"
    print(y)
except NameError:    
    print("Name Error Exception is Caught")

Output:

Exception is caught

The try block allows us to check and see that our code will throw an error or not. We can use this block to trail our code to see if there may be potential for errors to occur.

The Except Block will allow us to write the part where we want to handle the error. We can use this block to denote the user on want went wrong without the console throwing errors.

We can also use a Finally block along with try and except to continuously run the code without termination by indicating only the exception message.

Example:

Finally, block.

Code:

name='Smith'
try:
    print("Hello" " "+ name)
except NameError:
    print("Name is not denoted")
finally:
    print("Have a nice day")

Output:

Finally block

Since the name is denoted, the code has successfully run without throwing the exception. Below we have deleted the name denoted we can see the exception message thrown.

Code:

name='Smith'
try:
    print("Hello" " "+ name)
except NameError:
    print("Name is not denoted")
finally:
    print("Have a nice day")
    del name    
try:
    print("Hello " + name)
except NameError:
    print("Name is not denoted")

Output:

we can see the exception message thrown

The finally block allows us to run the code without termination since the name denoted is deleted. The finally blocks will get executed even if the try block raises an exception message. We can use this technique to overcome the NameError.

Conclusion

The main take away to remember in python NameError is the failure of the interpreter to identify the name or text we have used in our code. We have seen in detail about the NameError that occurs in the Python programming language and the techniques to overcome the NameError.

Recommended Articles

This is a guide to Python NameError. Here we discuss how NameError works and avoiding NameErrors in python, respectively. You may also have a look at the following articles to learn more –

  1. Python Input String
  2. Python String Operations
  3. Python Sort List
  4. Python Constants

Понравилась статья? Поделить с друзьями:
  • Excel сбой активации продукта как исправить 2019
  • Excel разндат ошибка число
  • Excel проверка на ошибку
  • Excel ошибка ссылка как исправить
  • Excel ошибка слишком много различных форматов ячеек