Name error is not defined 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».

NameErrors are one of the most common types of Python errors. When you’re first getting started, these errors can seem intimidating. They’re not too complicated. A NameError means that you’ve tried to use a variable that does not yet exist.

In this guide, we’re going to talk about the “nameerror name is not defined” error and why it is raised. We’ll walk through a few example solutions to this error to help you understand how to resolve it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is a NameError?

A NameError is raised when you try to use a variable or a function name that is not valid.

In Python, code runs from top to bottom. This means that you cannot declare a variable after you try to use it in your code. Python would not know what you wanted the variable to do.

The most common NameError looks like this:

nameerror name is not defined

Let’s analyze a few causes of this error.

Cause #1: Misspelled Variable or Function Name

It’s easy for humans to gloss over spelling mistakes. We can easily tell what a word is supposed to be even if it is misspelled. Python does not have this capability.

Python can only interpret names that you have spelled correctly. This is because when you declare a variable or a function, Python stores the value with the exact name you have declared.

If there is a typo anywhere that you try to reference that variable, an error will be returned.

Consider the following code snippet:

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

print(boooks)

Our code returns:

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

To solve this problem, all we have to do is fix the typo. If we use “print(books)”, our code returns:

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

If you receive a name error, you should first check to make sure that you have spelled the variable or function name correctly.

Cause #2: Calling a Function Before Declaration

Functions must be declared before they are used, like variables. This is because Python reads code from top-to-bottom. 

Let’s write a program that calls a function before it is declared:

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

print_books(books)

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

Our code returns:

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

We are trying to call print_books() on line three. However, we do not define this function until later in our program. To fix this error, we can move our function declaration to a place before we use it:

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

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

print_books(books)

Our code returns:

Near Dark
The Order
Where the Crawdads Sing

Our code has successfully printed out the list of books.

Cause #3: Forget to Define a Variable

As programs get larger, it is easy to forget to define a variable. If you do, a name error is raised. This is because Python cannot work with variables until they are declared.

Let’s take a look at a program that prints out a list of books:

Our code returns: 

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

We have not declared a variable called “books”. To solve this problem, we need to declare “books” before we use it in our code:

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

for b in books:
print(b)

Let’s try to run our program again and see what happens:

Near Dark
The Order
Where the Crawdads Sing

Now that we have defined a list of books, Python can print out each book from the list.

Cause #4: Try to Print a Single Word

To print out a word in Python, you need to surround it in either single or double quotes. This tells Python that a word is a string. If a word is not surrounded by quotes, it is treated as part of a program. Consider the following print() statement:

This code tries to print the word “Books” to the console. The code returns an error:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

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

Python treats “Books” like a variable name. To solve this error, we can enclose the word “Books” in quotation marks:

Python now knows that we want to print out a string to the console. Our new code returns: Books.

Cause #5: Declaring a Variable Out of Scope

There are two variable scopes: local and global.

Local variables are only accessible in the function or class in which they are declared. Global variables are accessible throughout a program.

If you try to access a local variable outside the scope in which it is defined, an error is raised.

The following code should print out a list of books followed by the number of books in the list:

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

print_books()
print(len(books))

Our code returns:

Near Dark
The Order
Where the Crawdads Sing
Traceback (most recent call last):
  File "main.py", line 6, in <module>
	print(len(books))
NameError: name 'books' is not defined

Our code successfully prints out the list of books. On the last line of our code, an error is returned. While we have declared the variable “books”, we only declared it inside our print_books() function. This means the variable is not accessible to the rest of our program.

To solve this problem, we can declare books in our main program. This will make it a global variable:

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

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

print_books()
print(len(books))

Our code returns:

Near Dark
The Order
Where the Crawdads Sing
3

Our code prints out every book in the “books” list. Then, our code prints out the number of books in the list using the len() method.

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 is one of the most common Python exceptions. And the »

NameError: name is not defined

Python Error» occurs in Python when we try to access a Python variable before initializing or defining it.

In this Python guide, we will walk through this Python error and discuss how to debug it. We will also use some examples to demonstrate this Python error to get a better idea of how to solve this error in your Program.

The NameError is raised in Python when we try to access a variable or function, and Python is not able to find that name, because it is not defined in the program or imported libraries.


For example

message = "Hello World!"

print(Message)


Output

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


Break the code

Python is a case-sensitive programming language, which means if the cases of the two variables are different Python will treat them as different variables.

In the above program in line 1, we have defined a variable by name

message

but in line 3 we are printing the variable

Message

, which is a totally different variable and not defined in the program.

That’s why we are getting the

NameError: name 'Message' is not defined

Error, which is telling us that the variable

Message

is not defined in the program.

You can also receive this similar error with the following error message



  • nameerror: name ‘data’ is not defined


    : When you are trying to access a data variable without defining it.
  • nameerror: name ‘X’ is not defined: When you are trying to access any X variable without defining it.


Note:

The «nameerror name is not defined» is a very common error and it can easily be solved by analyzing the code, and the line where you are receving that error.


Solution

The solution of the above example is very simple. We only need to make sure that the variable we are accessing has the same name as we have defined earlier in the program.


Example Solution

message = "Hello World!"

print(message)


Output

Hello World!


Common Error Examples

There are many common scenarios where many new and experienced Python learners commit mistakes while writing programs and encounter Python NameError.

  1. Misspelt the variable or function name
  2. Try to call a variable or function before the declaration
  3. Forget to define a variable
  4. Trying to access a local variable.


Scenario 1: Missplet the variable or function name

This happened many times when the programmer misspelt the defined variable or function name, during accessing the variable or function. Python is a case-sensitive programming language, and even a single letter misspelt or case change is treated as a completely different variable or function name.


Example

def say_hello(message):
    print(message)

# the message to print
message = "Welcome to techgeekbuzz"

# error
sayhello(message)


Output

Traceback (most recent call last):
File "main.py", line 8, in <module>
sayhello(message)
NameError: name 'sayhello' is not defined


Break the code

We are getting this NameError in the above program because we are trying to call the function

sayhello()

that is not defined in the program. The function in the program is defined by the name

say_hello

and we are calling the function

sayhello

which is two different function names, that’s why Python is throwing the NameError.


Solution

To solve the above problem we need to make sure that the name of the function during the function call must be the same as the function name defined using the

def

keyword.

def say_hello(message):
    print(message)

# the message to print
message = "Welcome to techgeekbuzz"

# print message
say_hello(message)


Output

Welcome to techgeekbuzz


Scenario 2: Try to call a variable or function before the declaration

Python is an interpreted programming language, and it executes its program code line by line, so before calling a function or accessing a variable value, it must be declared or defined. The function declaration and the variable initialization must be done before calling a function or accessing a variable, otherwise, we will receive the NameError.


Example

# the message to print
message = "Welcome to techgeekbuzz"

# function call
say_hello(message)

# declare function after funtion call
def say_hello(message):
    print(message)


Output

Traceback (most recent call last):
File "main.py", line 5, in <module>
say_hello(message)
NameError: name 'say_hello' is not defined


Break the code

In the above program, we are getting the NameError for the

say_hello(message)

function call statement. This is because the Python interpreter starts its execution from the top line of the program, and it keeps executing the program code line by line until it encounters an exception or error.

In the above program when the Python interpreter reached line 5 and try to execute the

say_hello(message)

statement, it found that it has no function declaration statement by name

say_hello()

to call, so instead of executing the below further code Python raise the NameError that there is no name defined with

say_hello

.


Solution

To solve the above problem, we just move the function definition part above the function calling statement. So the Python interpreter could store the

say_hello()

function in the heap memory, and execute it when the function is called.

# the message to print
message = "Welcome to techgeekbuzz"

# declare function before the funtion call
def say_hello(message):
    print(message)

# function call
say_hello(message)


Output

Welcome to techgeekbuzz


Scenario 3: Forget to define a variable

Many times we have a variable in mind but we forget to define it in the program. And when we try to access it, we receive the NameError.


Example

name = "Rahul"

print("Name:",name, "nAge:", age )


Output

Traceback (most recent call last):
File main.py", line 3, in <module>
print("Name:",name, "nAge:", age )
NameError: name 'age' is not defined


Break the Code

In the above program, we are trying to print the

age

variable that we haven’t defined. That’s why we are receiving the NameError.


Solution

To resolve the above error, we also need to define the age variable and its value before the print statement.

name = "Rahul"
age = 30

print("Name:",name, "nAge:", age )


Output

Name: Rahul 
Age: 30


Scenario 4: Try to Access a Local Variable

In Python, there are two variable scopes

local and global

. The program space that is outside the function is known as the global scope and the program space inside the functions is known as the local scope. The variables defined in the global scope are known as global variables, and the variables defined inside the local scope are known as local variables.

The global variable can be accessed through any scope, but a local variable can only be accessed in its local scope(inside the function). If we try to access the local scope variable outside its

function scope

we get the NameError.


Example

names = ["rahul", 'rajesh', 'aman', 'vikash']

def add_name(name):
    # local variable total
    total = len(names)

    # add new name to names
    names.append(name)

# add new name to names list
add_name("ravi")

# access all names
print(names)

# accessing local variable total
print(total)


Output

['rahul', 'rajesh', 'aman', 'vikash', 'ravi']
Traceback (most recent call last):
File "main.py", line 17, in <module>
print(total)
NameError: name 'total' is not defined


Break the Code

In the above program, we are encountering the NameError at line 17 with

print(total)

statement. We are receiving this nameerror» because we are trying to print the

total

variable value in the global scope, and the name is not defined in the local scope of

add_name()

function.


Solution

We can not access a local variable outside the function, but if we want the value of the local variable, we can return it using the function return statement and save that value in a global variable with the same name.

names = ["rahul", 'rajesh', 'aman', 'vikash']

def add_name(name):
    # add new name to names
    names.append(name)

    # local variable total
    total = len(names)

    # return the value of total
    return total

# add new name to names list
total = add_name("ravi")

# access all names
print(names)

# print the value of total
print(total)


Output

['rahul', 'rajesh', 'aman', 'vikash', 'ravi']
5


Wrapping Up!

NameError is a common exception in Python, it is raised when the Python interpreter is not able to fnc the local or global name of the variable in the Program and imported libraries. To resolve this error, we have to look out for the error line and make sure that the name we are using to access a variable or call a function must be defined in the Program.

If you are still getting this error in your Python program, please share your code in the comment section; we will try to help you in debugging.


To gain in-depth insights into Python Exception handling,

buy the course

here.


People are also reading:

  • Python TypeError: ‘float’ object is not subscriptable Solution

  • Python TypeError: list indices must be integers or slices, not tuple Solution

  • Python TypeError: ‘float’ object is not callable Solution

  • Python TypeError: ‘builtin_function_or_method’ object is not subscriptable Solution

  • Python TypeError: ‘int’ object is not callable Solution

  • Python indexerror: list assignment index out of range Solution

  • Python valueerror: could not convert string to float Solution

  • Python local variable referenced before assignment Solution

  • Python typeerror: string indices must be integers Solution

  • Python valueerror: too many values to unpack (expected 2) Solution

Понравилась статья? Поделить с друзьями:
  • Na camw error ciplus 0015
  • Na cama error ciplus 0015 триколор тв
  • N5i ошибка eberspacher
  • N201006 ошибка загрузки
  • N aurl запрещен к индексированию тегом noindex как исправить