Python script name error

NameError: name ‘X’ is not defined in Python

In Python, different types of errors occur when we use inappropriate values, inappropriate data types, or irrelevant data. One of the errors occurs in Python when the variable or function is used without defining it in the program, and this type of error is known as “NameError”.

This write-up will show you different reasons and solutions for “NameError: name X is not defined” in Python with multiple examples. The following contents are explained in this Python guide one by one in detail:

Reason 1: Variable or Function Does Not Exist

One of the main reasons for the “NameError: name ‘X’ is not defined” error in Python is accessing a variable/function that is not present in our script. In Python, to use a variable/function, we need to assign the value or declare it before accessing it in the program. Let’s have a look at the below example to have an idea of this error:

Читайте также:  Python black config file

The above code defines a function named “name” using the keyword “def”. This function is accessed and returns the value “5” successfully. But when we tried to access a sample() function, we encountered the “NameError”, which shows that the “name ‘sample’ is not defined”. This is because this function does not exist in the entire program.

Solution: Access the Declared Function or Function Which Exists

To solve this error, the function must be defined before accessing the function.

Value = 5 def name(): print(Value) def sample(): print(Value) name() sample()

In the above code, the integer is initialized, and after that, the two different functions are declared using the “def” keyword. Both functions are accessed at the end of the program.

Because both functions are defined before they are accessed in the code, the stated error has been resolved.

Reason 2: Accessing Before Declaring Function

In the below snippet, the function is accessed before declaring it in the program. The Python interpreter shows an error while executing it because the function or variable can not be accessed before the declaration.

In the above code, the function named “sample” is accessed before being declared.

Solution: Accessed Function After Declaring

Access the function after defining it in the program to fix the stated error.

Value = 5 def sample(): print(Value) sample()

In the above code, the function is accessed after the declaration of the function.

The output shows that the desired function has been accessed successfully.

Reason 3: Misspelled Variable or Function

The “NameError” also arises in the program when the variable or function name is misspelled while accessing or performing an operation on it.

During access to the “sample” function, the function name is misspelled. So, it throws an error.

Note: Python is case-sensitive, so it throws an error if the letter case is ignored when accessing functions.

Solution: Correct the Misspelled Variable or function

In the below code snippet, the error is fixed by correcting the misspelled function name.

Value = 5 def sample(): print(Value) sample()

In the above code, the function is accessed at the end of the program using the name of the function with parentheses.

From the above output, it is verified that the function is accessed successfully without any error.

Reason 4: Not Enclosing String in Quotes

The error arises when the string value is not defined inside the single or double quotation marks.

An example of this is shown below:

In the above code, the string name “David” is not enclosed with single or double quotes. That’s why the “NameError” appeared on the output console of the interpreter.

Solution: Enclosed the String in Single or Double Quotes

To rectify this error, the string value must be placed inside the single or double quotes, as shown in the below code:

def Students(name): print('Hello' + name) Students(' David')

In the above code, a function named “Students” is defined and accepts the parameter value of the name inside the parentheses.

The string value has been successfully added to another string in the above output.

Reason 5: Not Enclosing Dictionary Key in Quotes

Like simple string values, dictionary key values must be enclosed with single or double quotation marks.

The above code initializes the dictionary value in a variable named “dict_value”. The key “Age” of the dictionary is not enclosed within quotes.

Solution: Enclosed Dictionary Keys Within the Quotes

To fix the “NameError”, wrap the dictionary key within single quotes. Let’s experience it via the following code:

dict_value = print(dict_value)

In the above code, the dictionary value is initialized, and the key values are enclosed within the quotes.

The dictionary value has been successfully created in the above output.

Reason 6: Using Built-in Module With Importing

The error also arises when in the Python program, the inbuilt function of the standard module is used without importing it at the program’s start.

In the above code, the “math.floor()” function of the standard module named “math” is used without importing the math module.

Solution: Import the Module at the Start

To correct this error, the math module is imported at the start of the program, as shown in the below snippet:

dict_value = print(dict_value)

In the above code, the math module function “math.floor()” takes the input variable as an argument and returns the floor value.

The above output shows the floor value of the input number.

This Python Guide has come to an end!

Conclusion

The “NameError: name ‘X’ is not defined” occurs in Python when the operated variable or function is accessed before defining it or not defined in the program. To solve this error, the variable or function must be defined in the program before accessing. The functions and variables must be accessed with the correct spelling. The standard module must be imported at the start or before using/accessing the function. This Python post presented a detailed overview of different reasons and solutions for “NameError: name ‘X’ is not defined” in Python.

Источник

Как исправить ошибку NameError в Python

Первый шаг в исправлении ошибок при написании кода — понять, что именно пошло не так. И хотя некоторые сообщения об ошибках могут показаться запутанными, большинство из них помогут вам понять, что же не работает в вашей программе. В этой статье мы поговорим о том, как исправить ошибку NameError в Python. Мы рассмотрим несколько примеров кода, показывающих, как и почему возникает эта ошибка, и покажем, как ее исправить.

Что такое NameError в Python?

В Python ошибка NameError возникает, когда вы пытаетесь использовать переменную, функцию или модуль, которые не существуют, или использовать их недопустимым образом.

Некоторые из распространенных причин, вызывающих эту ошибку:

  • Использование имени переменной или функции, которое еще не определено
  • Неправильное написание имени переменной/функции при её вызове
  • Использование модуля в Python без импорта этого модуля и т. д.

Как исправить «NameError: Name Is Not Defined» в Python

В этом разделе мы рассмотрим, как исправить ошибку NameError: Name is Not Defined в Python.

Мы начнем с блоков кода, вызывающих ошибку, а затем посмотрим, как их исправить.

Пример №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. Также мы показали, как можно исправить эти ошибки.

Надеемся, данная статья была вам полезна! Успехов в написании кода!

Источник

Оцените статью