search
HomeBackend DevelopmentPython TutorialHow to solve the 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 this error, we need to make sure we didn't misspell the variable name and access it after declaring it.

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) # ????️ 拼写错误的变量名

How to solve the Python error NameError:name X is not defined

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

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

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

print(employee)

## Access non-existing variables.

    Access a variable, function, or class before declaring it.
  • The name of a variable, function, or class is misspelled (names are case-sensitive).
  • Do not enclose strings in quotes, such as print(hello).
  • Do not enclose dictionary keys in quotes.
  • Use built-in modules without importing them first.
  • Access scope variables from outside. For example, declare a variable in a function and try to access it from outside.
  • Accessing non-existing variables or functions
  • #Make sure we are not accessing variables that do not exist or have not been defined yet.
  • Accessing non-existing variables or functions
  • Make sure we are not accessing variables that do not exist or have not 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 this error, move the line that calls the function or accesses the variable after declaring it.

# ✅ 1) 声明函数或变量
def do_math(a, b):
    return a + b

# ✅ 2) 之后访问它
print(do_math(15, 15))  # ????️ 30

Please note that we must also instantiate the class or call the class method after the class declaration.

The same is true when using variables.

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

variable = 'jiyik.com'

Make sure to move the line accessing the variable below the line declaring it.

variable = 'jiyik.com'

print(variable)  # ????️ jiyik.com

Forgetting to enclose a string in single or double quotes

Another cause of the error is forgetting to enclose a string in single or double quotes.

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


# ⛔️ NameError: name 'Fql' is not defined. Did you mean: 'slice'?
greet(Fql) # ????️ 忘记用引号括起字符串

greet function expected to be called with a string, but we forgot to put the string in quotes, so an error with name 'X' being undefined occurred.

This also occurs when passing a string to the

print()

function without surrounding the string in quotes.

To resolve this error, enclose the string in quotes.

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

greet('Fql')
Using a built-in module without importing itIf we use a built-in module without importing it, it will also cause "
NameError: name is not defined

".

# ⛔️ NameError: name 'math' is not defined
print(math.floor(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 have not imported the module before accessing the property.

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

import math
print(math.floor(15.5))  # ????️ 15
import math

line is required because it loads the

math

module into our code.

A module is just a collection of functions and classes. We must load the module before we can access its members. Forgetting to enclose the keys of the dictionary in quotes

This error can also be caused if we have a dictionary and forget to enclose its keys in quotes.

employee = {
    'name': 'Jiyik',
    # ⛔️ NameError: name 'age' is not defined
    age: 30 # ????️ 字典键未包含在引号中
}

Unless you have numeric keys in the dictionary, make sure to enclose them in single or double quotes.

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

Trying to access scope variable from outside

This error also occurs if we try to access scope variable from outside.

def get_message():
    message = 'jiyik.com' # ????️ 函数中声明的变量
    return message


get_message()

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

message

The variable is declared in the

get_message

function, so it cannot be accessed from the outer scope.

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

# ????️ 在外部范围内声明变量
message = 'hello world'

def get_message():
    return message


get_message()

print(message)  # ????️ "hello world"
An alternative in this case is to return the value from the function and store it in a variable. <pre class="brush:php;toolbar:false">def get_message():     message = 'jiyik.com'     return message result = get_message() print(result)  # ????️ &quot;hello world&quot;</pre>Another option is to mark the variable as global.

def get_message():
    # ????️ 将 message 标记为全局
    global message

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

    return message


get_message()

print(message)  # ????️ "hello world"

Please note that

, generally the
global

keyword should be avoided as it will make our code harder to read and reasoning. Trying to access a variable declared in a nested function If we try to access a variable declared in a nested function from an outer function, we can mark the variable as non-local variable.

def outer():
    def inner():
        message = 'jiyik.com'
        print(message)

    inner()

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


outer()
The inner function declares a variable named
message

but we try to access the variable from the outer function and get the "name message is not defined" error.

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

def outer():
    # ????️ 初始化 message 变量
    message = ''

    def inner():
        # ????️ 将 message 标记为 nonlocal
        nonlocal message
        message = 'jiyik.com'
        print(message)

    inner()

    print(message)  # ????️ "jiyik.com"


outer()

nonlocal keyword allows us to use local variables of the enclosing function.

请注意 ,我们必须在外部函数中初始化消息变量,但我们能够在内部函数中更改它的值。

如果我们不使用 nonlocal 语句,对 print() 函数的调用将返回一个空字符串。

def outer():
    # ????️ 初始化 message 变量
    message = ''

    def inner():
        # ????️ 在内部范围内声明 message
        message = 'hello world'
        print(message)

    inner()

    print(message)  # ????️ ""

outer()

在类定义之前访问它

当我们在定义类之前访问类时,也会发生该错误。

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


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

    def get_name(self):
        return self.name

要解决该错误,请将实例化行移至类声明下方。

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

    def get_name(self):
        return self.name


emp1 = Employee('jiyik', 100)
print(emp1.name)  # ????️ jiyik

如果我们正在使用来自第三方库的类,则必须先导入该类才能使用它。

请注意在 try/except 块中使用 import 语句

try/except 块中使用 import 语句时也可能发生该错误。

try:
    # ????️ 此处的代码可能会引发错误

    import math
    result = math.floor(15.5)

except ImportError:
    math.floor(18.5)

print(math.floor(20.5))

该代码示例有效,但是,如果 import 语句之前的某些代码引发错误,则该模块将不会被导入。

这是一个问题,因为我们正在 except 块中和 try/except 语句之外访问模块。

相反,将导入语句移至文件顶部。

# ✅ 将 import 语句移动到文件顶部
import math

try:
    result = math.floor(15.5)

except ImportError:
    math.floor(18.5)

print(math.floor(20.5))

The above is the detailed content of How to solve the Python error NameError:name 'X' is not defined. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

How do you create a Python array? Give an example.How do you create a Python array? Give an example.May 04, 2025 am 12:10 AM

Pythonarraysarecreatedusingthearraymodule,notbuilt-inlikelists.1)Importthearraymodule.2)Specifythetypecode,e.g.,'i'forintegers.3)Initializewithvalues.Arraysofferbettermemoryefficiencyforhomogeneousdatabutlessflexibilitythanlists.

What are some alternatives to using a shebang line to specify the Python interpreter?What are some alternatives to using a shebang line to specify the Python interpreter?May 04, 2025 am 12:07 AM

In addition to the shebang line, there are many ways to specify a Python interpreter: 1. Use python commands directly from the command line; 2. Use batch files or shell scripts; 3. Use build tools such as Make or CMake; 4. Use task runners such as Invoke. Each method has its advantages and disadvantages, and it is important to choose the method that suits the needs of the project.

How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools