SoFunction
Updated on 2024-12-19

Solution to Python error NameError:name 'X' is not defined

Python“NameError: name is not defined"Occurs when we try to access an undefined variable or function, or before it is defined.

To fix the error, we need to make sure we are not misspelling the variable name and accessing it after declaration.

Make sure you don't misspell a variable or function

Below is the sample code that produces the above error.

employee = {
    'name': 'Jiyik',
    'age': 30,
}

# ⛔️ NameError: name 'Employee' is not defined. Did you mean: 'employee'?
print(Employee) # 👈️ misspelled variable names

Python 错误 NameError name X is not defined

The problem is that we misspelled the variable names. Note that variable, function and class names are case sensitive.

To fix the error in this case, we must spell the variable name correctly.

employee = {
    'name': 'Jiyik',
    'age': 30,
}

print(employee)

Common Causes of 'X' is not defined Errors

"Python" appears.NameError: name is not defined"There are various reasons for this:

  • Access to non-existing variables.
  • Access a variable, function, or class before it is declared.
  • The name of a variable, function, or class is misspelled (names are case sensitive).
  • Do not cause strings to be quoted, e.g. print(hello).
  • Does not cause dictionary keys to be in quotes.
  • Use the built-in modules without importing them first.
  • Accessing a scope variable from the outside. For example, declaring a variable in a function and trying to access it externally.
  • Accessing a non-existent variable or function#
  • Make sure we're not accessing variables that don't exist or haven't been defined yet.

Accessing non-existent variables or functions

Make sure we're not accessing variables that don't exist or haven't been defined yet.

# ⛔️ NameError: name 'do_math' is not defined
print(do_math(15, 15))


def do_math(a, b):
    return a + b

The code example results in a "NameError: function is not defined" error because we are trying to call the function before it is declared.

To resolve the error, move the line that calls the function or accesses the variable after declaring it.

# ✅ 1) Declaring a function or variable
def do_math(a, b):
    return a + b

# ✅ 2) Visit it later
print(do_math(15, 15))  # 👉️ 30

Note that we must also instantiate the class or call the class methods after the class declaration.

The same is true when using variables.

# ⛔️ NameError: name 'variable' is not defined.
print(variable)

variable = ''

Make sure to move the line that accesses the variable below the line that declares it.

variable = ''

print(variable)  # 👉️ 

Forgetting to enclose a string in single or double quotes

Another reason for the error is forgetting to cause the string in single or double quotes.

def greet(name):
    return 'Hello ' + name

# ⛔️ NameError: name 'Fql' is not defined. Did you mean: 'slice'?
greet(Fql) # 👈️ Forgot to enclose string in quotes

The greet function is expected to be called with a string, but we forgot to put the string in quotes, hence the undefined name "X" error.

When passing a string to theprint() function without using quotes to bring the string into existence, this also happens.

To resolve the error, enclose the string in quotation marks.

def greet(name):
    return 'Hello ' + name

greet('Fql')

Using the built-in module without importing it

If we use the built-in module without importing it, it will also result in "NameError: name is not defined”。

# ⛔️ NameError: name 'math' is not defined
print((15.5))

We use the math module without importing it first, so Python doesn't know what math refers to.

"NameError: name 'math' is not defined" means that we are trying to access a function or property on the math module, but we haven't imported the module before accessing the property.

To resolve the error, make sure to import all the modules we are using.

import math
print((15.5))  # 👉️ 15

import math line is required because it willmath module is loaded into our code.

Modules are just collections of functions and classes.

We must load the module before we can access its members.

Forgetting to enclose dictionary keys in quotation marks

This error can also result if we have a dictionary and forget to enclose its keys in quotation marks.

employee = {
    'name': 'Jiyik',
    # ⛔️ NameError: name 'age' is not defined
    age: 30 # 👈️ Dictionary key not contained in quotes
}

Unless there are numeric keys in the dictionary, be sure to cause them with single or double quotes.

employee = {
    'name': 'Jiyik',
    'age': 30
}

Trying to access a scope variable externally

This error also occurs if we try to access the scope variable externally.

def get_message():
    message = '' # 👈️ Variables declared in functions
    return message

get_message()

# ⛔️ NameError: name 'message' is not defined
print(message)

message The variable is in theget_message declared in the function, so it cannot be accessed from an external scope.

If a variable must be accessed externally, the best solution is to declare the variable in an external scope.

# 👇️ Declaring variables in external scope
message = 'hello world'

def get_message():
    return message

get_message()

print(message)  # 👉️ "hello world"

In this case, another approach is to return the value from the function and store it in a variable.

def get_message():
    message = ''
    return message

result = get_message()

print(result)  # 👉️ "hello world"

Another option is to mark the variable as a global variable.

def get_message():
    # 👇️ Mark message as global
    global message

    # 👇️ change its value
    message = 'hello world'

    return message

get_message()

print(message)  # 👉️ "hello world"

please note The use of the term "P" should be avoided as a general rule.global keyword because it makes our code harder to read and reason about.

Attempts to access variables declared in nested functions

If we try to access a variable declared in a nested function from an external function, we can mark the variable as non-local.

def outer():
    def inner():
        message = ''
        print(message)

    inner()

    # ⛔️ NameError: name 'message' is not defined
    print(message)

outer()

The internal function declares a function namedmessage but we try to access the variable from an external function and get a "name message is not defined" error.

To solve this problem, we can mark message variables as non-local.

def outer():
    # 👇️ Initialize the message variable
    message = ''

    def inner():
        # 👇️ Marks message as nonlocal
        nonlocal message
        message = ''
        print(message)

    inner()

    print(message)  # 👉️ ""

outer()

nonlocal keyword allows us to use local variables of closed functions.

please note , we have to initialize the message variable in an external function, but we are able to change its value in an internal function.

If we don't use thenonlocal statements, to theprint() The function call will return an empty string.

def outer():
    # 👇️ Initialize the message variable
    message = ''

    def inner():
        # 👇️ Declare message in internal scope
        message = 'hello world'
        print(message)

    inner()

    print(message)  # 👉️ ""

outer()

Accessing a class before it is defined

This error also occurs when we access the class before defining it.

# ⛔️ NameError: name 'Employee' is not defined
emp1 = Employee('jiyik', 100)

class Employee():
    def __init__(self, name, salary):
         = name
         = salary

    def get_name(self):
        return 

To resolve the error, move the instantiation line below the class declaration.

class Employee():
    def __init__(self, name, salary):
         = name
         = salary

    def get_name(self):
        return 

emp1 = Employee('jiyik', 100)
print()  # 👉️ jiyik

If we are using a class from a third-party library, we must import the class before we can use it.

Note the use of the import statement in the try/except block.

existtry/except block using theimport This error may also occur when the statement

try:
    # 👉️ The code here may raise an error

    import math
    result = (15.5)

except ImportError:
    (18.5)

print((20.5))

This code example works, however, ifimport Some code before the statement raises an error, then the module will not be imported.

This is a problem because we're in the except block and thetry/except Access the module outside of the statement.

Instead, move the import statement to the top of the file.

# ✅ Move the import statement to the top of the file
import math

try:
    result = (15.5)

except ImportError:
    (18.5)

print((20.5))

summarize

To solve Python "NameError: name is not defined"Make sure:

  • We don't have access to variables that don't exist.
  • We don't access a variable, function or class before declaring it.
  • We didn't misspell the name of a variable, function, or class (names are case sensitive).
  • We didn't forget to enclose a string in quotes, such as print(hello).
  • We didn't forget to enclose the dictionary keys in quotation marks.
  • If you don't import the built-in modules first, you won't use them.
  • We are not accessing scope variables from the outside. For example, declaring a variable in a function and trying to access it externally.

To this point this article on Python error NameError: name 'X' is not defined solution to the article is introduced to this, more related Python error NameError: name 'X ' is not defined content please search my previous posts or continue to browse the following related articles I hope you will support me more in the future!