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

王林
Release: 2023-04-28 12:22:15
forward
1713 people have browsed it

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

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)
Copy after login

## 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
    Copy after login
  • 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
Copy after login

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'
Copy after login

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

variable = 'jiyik.com'

print(variable)  # ????️ jiyik.com
Copy after login

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) # ????️ 忘记用引号括起字符串
Copy after login

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')
Copy after login
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))
Copy after login

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
Copy after login
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 # ????️ 字典键未包含在引号中
}
Copy after login

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

employee = {
    'name': 'Jiyik',
    'age': 30
}
Copy after login

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)
Copy after login

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"
Copy after login
An alternative in this case is to return the value from the function and store it in a variable. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">def get_message():     message = 'jiyik.com'     return message result = get_message() print(result)  # ????️ &quot;hello world&quot;</pre><div class="contentsignin">Copy after login</div></div>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"
Copy after login

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()
Copy after login
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()
Copy after login

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()
Copy after login

在类定义之前访问它

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

# ⛔️ 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
Copy after login

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

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
Copy after login

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

请注意在 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))
Copy after login

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

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

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

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

try:
    result = math.floor(15.5)

except ImportError:
    math.floor(18.5)

print(math.floor(20.5))
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template