- Python nameerror name is not defined Solution
- What is a NameError?
- Cause #1: Misspelled Variable or Function Name
- Cause #2: Calling a Function Before Declaration
- Cause #3: Forget to Define a Variable
- Cause #4: Try to Print a Single Word
- Cause #5: Declaring a Variable Out of Scope
- 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
- NameError: Name plot_cases_simple is Not Defined – How to Fix this Python Error
- What Is a NameError in Python?
- How to Fix «NameError: Name Is Not Defined» in Python
- Example #1 — Variable Name Is Not Defined in Python
- Example #2 — Function Name Is Not Defined in Python
- Example #3 — Using a Module Without Importing the Module Error in Python
- Summary
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.
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.
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)
Traceback (most recent call last): File "main.py", line 3, in 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)
Traceback (most recent call last): File "main.py", line 3, in 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)
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:
Traceback (most recent call last): File "main.py", line 1, in 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:
«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 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))
Near Dark The Order Where the Crawdads Sing Traceback (most recent call last): File "main.py", line 6, in 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))
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.
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
James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tuto. read more
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.
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.
Find a top-rated training program
NameError: Name plot_cases_simple is Not Defined – How to Fix this Python Error
Ihechikara Vincent Abba
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.
How to Fix «NameError: Name Is Not Defined» in Python
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.
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.
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.