Python ошибка nameerror name is not defined

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».

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.

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Prerequisites: Python Exception Handling

There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :

1. Misspelled built-in functions:

In the below example code, the print statement is misspelled hence NameError will be raised.

Python3

geek = input()

print(geek)

Output : 

NameError: name 'print' is not defined

2. Using undefined variables:

When the below program is executed, NameError will be raised as the variable geek is never defined.

Python3

geeky = input()

print(geek)

 
Output : 

NameError: name 'geek' is not defined

3. Defining variable after usage:

In the following example, even though the variable geek is defined in the program, it is defined after its usage. Since Python interprets the code from top to bottom, this will raise NameError

Python3

print(geek)

geek = "GeeksforGeeks"

 
Output : 

NameError: name 'geek' is not defined

4. Incorrect usage of scope:

In the below example program, the variable geek is defined within the local scope of the assign function. Hence, it cannot be accessed globally. This raises NameError.

Python3

def assign():

    geek = "GeeksforGeeks"

assign()

print(geek)

 
Output : 

NameError: name 'geek' is not defined

Handling NameError

To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.

Python3

def geek_message():

    try:

        geek = "GeeksforGeeks"

        return geeksforgeeks

    except NameError:

        return "NameError occurred. Some variable isn't defined."

print(geek_message())

Output : 

NameError occurred. Some variable isn't defined.

Last Updated :
29 Jan, 2022

Like Article

Save Article

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.

Понравилась статья? Поделить с друзьями:
  • Python ошибка int object is not callable
  • Python ошибка dataframe object is not callable
  • Python ошибка api ms win
  • Python обработка ошибок и исключений
  • Python обработка ошибок в цикле