Ошибка nameerror python

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

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

В этом руководстве поговорим об ошибке «NameError name is not defined». Разберем несколько примеров и разберемся, как эту ошибку решать.

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

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

Самая распространенная NameError выглядит вот так:

NameError: name 'some_name' is not defined

Разберем частые причина возникновения этой ошибки.

Причина №1: ошибка в написании имени переменной или функции

Для человека достаточно просто сделать опечатку. Также просто для него — найти ее. Но это не настолько просто для Python.

Язык способен интерпретировать только те имена, которые были введены корректно. Именно поэтому важно следить за правильностью ввода всех имен в коде.

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

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
print(boooks)

Он вернет:

Traceback (most recent call last):
  File "main.py", line 3, in 
	print(boooks)
NameError: name 'boooks' is not defined

Для решения проблемы опечатку нужно исправить. Если ввести print(books), то код вернет список книг.

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

Причина №2: вызов функции до объявления

Функции должны использоваться после объявления по аналогии с переменными. Это связано с тем, что Python читает код сверху вниз.

Напишем программу, которая вызывает функцию до объявления:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print_books(books)

def print_books(books):
	for b in books:
		print(b)

Код вернет:

Traceback (most recent call last):
  File "main.py", line 3, in 
	print_books(books)
NameError: name 'print_books' is not defined

На 3 строке мы пытаемся вызвать print_books(). Однако эта функция объявляется позже.

Чтобы исправить эту ошибку, нужно перенести функцию выше:

def print_books(books):
	for b in books:
		print(b)

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print_books(books)

Причина №3: переменная не объявлена

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

Посмотрим на программу, которая выводит список книг:

Такой код вернет:

Traceback (most recent call last):
  File "main.py", line 1, in 
	for b in books:
NameError: name 'books' is not defined

Переменная books объявлена не была.

Для решения проблемы переменную нужно объявить в коде:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

for b in books:
    print(b)

Причина №4: попытка вывести одно слово

Чтобы вывести одно слово, нужно заключить его в двойные скобки. Таким образом мы сообщаем Python, что это строка. Если этого не сделать, язык будет считать, что это часть программы. Рассмотрим такую инструкцию print():

Этот код пытается вывести слово «Books» в консоль. Вместо этого он вернет ошибку:

Traceback (most recent call last):
  File "main.py", line 1, in 
	print(Books)
NameError: name 'Books' is not defined

Python воспринимает «Books» как имя переменной. Для решения проблемы нужно заключить имя в скобки:

Теперь Python знает, что нужно вывести в консоли строку, и код возвращает Books.

Причина №5: объявление переменной вне области видимости

Есть две области видимости переменных: локальная и глобальная. Локальные переменные доступны внутри функций или классов, где они были объявлены. Глобальные переменные доступны во всей программе.

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

Следующий код пытается вывести список книг вместе с их общим количеством:

def print_books():
  books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
  for b in books:
      print(b)

print(len(books))

Код возвращает:

Traceback (most recent call last):
  File "main.py", line 5, in 
	print(len(books))
NameError: name 'books' is not defined

Переменная books была объявлена, но она была объявлена внутри функции print_books(). Это значит, что получить к ней доступ нельзя в остальной части программы.

Для решения этой проблемы нужно объявить переменную в глобальной области видимости:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

def print_books():
  for b in books:
      print(b)


print(len(books))

Код выводит название каждой книги из списка books. После этого выводится общее количество книг в списке с помощью метода len().

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

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

Некоторые из распространенных причин, вызывающих эту ошибку:

  • Использование имени переменной или функции, которое еще не определено
  • Неправильное написание имени переменной/функции при её вызове
  • Использование модуля в Python без импорта этого модуля и т. д.

Как исправить «NameError: Name Is Not Defined» в Python

В этом разделе мы рассмотрим, как исправить ошибку NameError: Name is Not Defined в Python.

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

[python_ad_block]

Пример №1. Имя переменной не определено

name = "John"

print(age)
# NameError: name 'age' is not defined

В приведенном выше коде мы определили переменную name, но далее попытались вывести переменную age, которая ещё не была определена.

Мы получили сообщение об ошибке: NameError: name 'age' is not defined. Это означает, что переменная age не существует, мы её не задали.

Чтобы исправить это, мы можем создать переменную, и наш код будет работать нормально. К примеру, это можно сделать следующим образом:

name = "John"
age = 12

print(age)
# 12

Теперь значение переменной age выводится без проблем.

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

name = "John"

print(nam)
# NameError: name 'nam' is not defined

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

Пример №2. Имя функции не определено

def sayHello():
    print("Hello World!")
    
sayHelloo()
# NameError: name 'sayHelloo' is not defined

В приведенном выше примере мы добавили лишнюю букву o при вызове функции — sayHelloo() вместо sayHello(). Это просто опечатка, однако она вызовет ошибку, потому что функции с таким именем не существует.

Итак, мы получили ошибку: NameError: name 'sayHelloo' is not defined. Подобные орфографические ошибки очень легко пропустить. Сообщение об ошибке обычно помогает исправить это.

Вот правильный способ вызова данной функции:

def sayHello():
    print("Hello World!")
    
sayHello()
# Hello World!

Как мы видели в предыдущем разделе, вызов переменной, которая еще не определена, вызывает ошибку. То же самое относится и к функциям.

К примеру, это может выглядеть так:

def sayHello():
    print("Hello World!")
    
sayHello()
# Hello World!

addTWoNumbers()
# NameError: name 'addTWoNumbers' is not defined

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

Обратите внимание, что вызов функции перед ее созданием приведет к той же ошибке. То есть такой код также выдаст вам ошибку:

sayHello()

def sayHello():
    print("Hello World!")
    
# NameError: name 'sayHello' is not defined

Поэтому вы всегда должны определять свои функции перед их вызовом.

Пример №3. Использование модуля без его импорта

x = 5.5

print(math.ceil(x))
# NameError: name 'math' is not defined

В приведенном выше примере мы используем метод математической библиотеки Python math.ceil(). Однако до этого мы не импортировали модуль math.

В результате возникает следующая ошибка: NameError: name 'math' is not defined. Это произошло потому, что интерпретатор не распознал ключевое слово math.

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

Вот так будет выглядеть исправленный код:

import math

x = 5.5

print(math.ceil(x))
# 6

В первой строке кода мы импортировали математический модуль math. Теперь, когда вы запустите приведенный выше код, вы получите результат 6. То же самое относится и ко всем остальным библиотекам. Сначала нужно импортировать библиотеку с помощью ключевого слова import, а потом уже можно использовать весь функционал этой библиотеки. Подробнее про импорт модулей можно узнать в статье «Как импортировать в Python?»

Заключение

В этой статье мы поговорили о том, как исправить ошибку NameError в Python.

Мы выяснили, что собой представляет NameError. Затем мы разобрали несколько примеров, которые могли вызвать ошибку NameError при работе с переменными, функциями и модулями в Python. Также мы показали, как можно исправить эти ошибки.

Надеемся, данная статья была вам полезна! Успехов в написании кода!

Перевод статьи «NameError: Name plot_cases_simple is Not Defined – How to Fix this Python Error».

NameError: Name plot_cases_simple is Not Defined – How to Fix this Python Error

This first step in fixing a coding error is to understand the error. Although some error messages may seem confusing, most of them will help you fix the error.

In this article, we’ll be talking about an error that falls under the NameError category in Python.

You’ll see what a NameError is, some code examples to show how/why the error occurs, and how to fix them.

What Is a NameError in Python?

In Python, the NameError occurs when you try to use a variable, function, or module that doesn’t exist or wasn’t used in a valid way.

Some of the common mistakes that cause this error are:

  • Using a variable or function name that is yet to be defined.
  • Misspelling a variable/function name when calling the variable/function.
  • Using a Python module without importing the module, and so on.

In this section, you’ll see how to fix the «NameError: Name is Not Defined» error in Python.

I’ve divided this section into sub-sections to show the error above when using variables, functions, and modules.

We’ll start with code blocks that raise the error and then see how to fix them.

Example #1 — Variable Name Is Not Defined in Python

name = "John"

print(age)
# NameError: name 'age' is not defined

In the code above, we defined a name variable but tried to print age which is yet t0 be defined.

We got an error that says: NameError: name 'age' is not defined to show that the age variable doesn’t exist.

To fix this, we can create the variable and our code will run fine. Here’s how:

name = "John"
age = 12

print(age)
# 12

Now the value of age gets printed out.

Similarly, the same error can be raised when we misspell a variable name. Here’s an example:

name = "John"

print(nam)
# NameError: name 'nam' is not defined

In the code above, we wrote nam instead of name.  To fix errors like this, you just have to spell the variable name the right way.

Example #2 — Function Name Is Not Defined in Python

def sayHello():
    print("Hello World!")
    
sayHelloo()
# NameError: name 'sayHelloo' is not defined

In the example above, we added an extra o while calling the function — sayHelloo() instead of sayHello().

We got the error: NameError: name 'sayHelloo' is not defined. Spelling errors like this are very easy to miss. The error message usually helps in fixing this.

Here’s the right way to call the function:

def sayHello():
    print("Hello World!")
    
sayHello()
# Hello World!

Just like we saw in the previous section, calling a variable that is yet to be defined raises an error. The same applies to functions.

Here’s an example:

def sayHello():
    print("Hello World!")
    
sayHello()
# Hello World!

addTWoNumbers()
# NameError: name 'addTWoNumbers' is not defined

In the code above, we called a function – addTWoNumbers() – that was yet to be defined in the program. To fix this, you can create the function if you need it or just get rid of the function if it is irrelevant.

Note that calling a function before creating it will throw the same error your way. That is:

sayHello()

def sayHello():
    print("Hello World!")
    
# NameError: name 'sayHello' is not defined

So you should always define your functions before calling them.

Example #3 — Using a Module Without Importing the Module Error in Python

x = 5.5

print(math.ceil(x))
# NameError: name 'math' is not defined

In the example above, we’re making use of the Python math.ceil method without importing the math module.

The resulting error was this: NameError: name 'math' is not defined. This happened because the interpreter did not recognize the math keyword.

Along with other math methods in Python, we must first import the math module to use it.

Here’s a fix:

import math

x = 5.5

print(math.ceil(x))
# 6

In the first line of the code, we imported the math module. Now, when you run the code above, you should have 6 returned.

Summary

In this article, we talked about the «NameError: Name is Not Defined» error in Python.

We first defined what a NameError is in Python.

We then saw some examples that could raise a NameError when working with variables, functions, and modules in Python. Each example, divided into sections, showed how to fix the errors.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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!

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

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка null что это значит
  • Ошибка null при обновлении iphone
  • Ошибка ntoskrnl exe windows 10 как исправить
  • Ошибка ntfs sys windows 10 при установке
  • Ошибка ntfs sys windows 10 как исправить

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

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