Ошибка NameError в Python
NameError — одна из самых распространенных ошибок в Python. Начинающих она может пугать, но в ней нет ничего сложного. Это ошибка говорит о том, что вы попробовали использовать переменную, которой не существует.
В этом руководстве поговорим об ошибке «NameError name is not defined». Разберем несколько примеров и разберемся, как эту ошибку решать.
Что такое NameError?
NameError возникает в тех случаях, когда вы пытаетесь использовать несуществующие имя переменной или функции.
В Python код запускается сверху вниз. Это значит, что переменную нельзя объявить уже после того, как она была использована. Python просто не будет знать о ее существовании.
Самая распространенная NameError выглядит вот так:
Разберем частые причина возникновения этой ошибки.
Причина №1: ошибка в написании имени переменной или функции
Для человека достаточно просто сделать опечатку. Также просто для него — найти ее. Но это не настолько просто для Python.
Язык способен интерпретировать только те имена, которые были введены корректно. Именно поэтому важно следить за правильностью ввода всех имен в коде.
Если ошибку не исправить, то возникнет исключение. Возьмем в качестве примера следующий код:
Python NameError: name is not defined
I have a python script and I am receiving the following error:
Here is the code that causes the problem:
This is being run with Python 3.3.0 under Windows 7 x86-64.
Why can’t the Something class be found?
![]()
4 Answers 4
Define the class before you use it:
You need to pass self as the first argument to all instance methods.
Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.
This will also result in
That’s because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.
![]()
You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.
You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:
I got the same error below:
NameError: name ‘name’ is not defined
When I don’t define the getter method with @property while the setter and deleter are defined as shown below:
Python nameerror name is not defined Solution
![]()
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.
At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources.
Career Karma receives compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

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
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:
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:
Our code returns:
To solve this problem, all we have to do is fix the typo. If we use “print(books)”, our code returns:
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:
Our code returns:
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:
Our code returns:
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:
We have not declared a variable called “books”. To solve this problem, we need to declare “books” before we use it in our code:
Let’s try to run our program again and see what happens:
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:

«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
Find Your Bootcamp Match
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:
Our code returns:
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:
Our code returns:
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.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
What’s Next?
Get matched with top bootcamps
Ask a question to our community
Take our careers quiz

![]()
Leave a Reply Cancel reply

Related Articles


At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.
Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.
It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.
In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.


Find a top-rated training program
How to Solve an Undefined Variable NameError in Python

In Python, a NameError: name ‘x’ is not defined error is raised when the program attempts to access or use a variable that has not been defined or assigned a value. This can happen if the variable is spelled incorrectly, or if it is accessed before it has been defined.
What Causes Undefined Variable
In Python, a variable is not created until a value is assigned to it. If an attempt is made to use a variable before it is defined, a NameError: name ‘x’ is not defined error is thrown.
The error message typically includes the name of the variable that is causing the problem and the line of code where the error occurred.
Python Undefined Variable Example
Here’s an example of a Python NameError: name ‘x’ is not defined thrown when using an undefined variable:
In this example, an undefined variable x is used in the range() function, throwing the NameError: name ‘x’ is not defined error:
How to Solve Undefined Variable in Python
To solve the NameError: name ‘x’ is not defined error in Python, you need to make sure that the variable is properly defined and assigned a value before it is used. The variable should also be referenced correctly, with the correct case and spelling.
The earlier example can be updated to define the variable before it is used:
Here, x is defined by being assigned a value before it is used in the range() function. The above code executes successfully, producing the correct output as expected:
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!