Technology

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.

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:

for b in books:
print(b)

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:

print(Books)

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

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:

print("Books")

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.



Click to rate this post!
[Total: 0]
Subscribe Our Newsletter Don't worry. We wont spam you.

Author

The Articledesk Editorial team is responsible for this post. For collaborations and partnership requests, kindly send an email to the Editorial Team at contact[at]articledesk[dot]net for the terms and conditions. You can also follow Articledesk.net on Twitter here and like our page on Facebook here.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Login for fast comment.

Login

close

About Us

We ensure that current articles are collected at one table for all writers and blog readers.

Follow Us