Py学习  »  Python

NameError:未在Python中定义名称“x”

Foldhy • 2 年前 • 998 次点击  

我试图避开这个错误,但找不到解决办法。事实上,代码在一段时间内运行良好,但突然开始删除错误:

"NameError: name 'number_exit' is not defined" 

而且:

"NameError: name 'price_buy' is not defined"

代码正在生成一个随机数列表

import numpy as np

# This function generates a list of numbers under certain rules
def num_var_list():
    global number_list, number_exit, number_target
    number_list = []
    number_target = number_exit
    num_max_robot = (number_target * 20) / 100
    while num_max_robot > 0:
        num_robot = np.random.randint(1,int(num_max_robot))
        if num_robot > number_target:
                number_list.append(number_target)
        else: 
            number_list.append(num_robot)
        number_target = number_target - number_target
    return number_list
        
# This function generates a random number between a certain range
def fun_price_buy():
    global price_buy
    price_buy = np.random.randint(50000,300000)
    return price_buy

# This function generates a random number between a certain range
def fun_mx_buy():
    global number_exit
    number_exit = np.random.randint(50, 150)
    return number_exit

lista_number_list = []
lista_price_buy = []
lista_mx_buy = []

# This loop append each function 50 times to a new list
while len(lista_price_buy) <= 50: 
    lista_number_list.append(num_var_list())
    lista_price_buy.append(fun_price_buy())
    lista_mx_buy.append(fun_mx_buy())

实际上,什么时候 Python 不会删除错误,代码完全符合我的要求。所以我不知道如何调整它,让它在没有名称错误警告的情况下工作。

任何帮助都将不胜感激。非常感谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130451
 
998 次点击  
文章 [ 5 ]  |  最新文章 2 年前
Random Davis
Reply   •   1 楼
Random Davis    3 年前

你还没有定义这些全局变量。打字 global whatever 不会自动定义一个名为 whatever .它只是告诉解释器存在一个名为 无论什么 在全球范围内。

例如,以下代码不会产生错误:

blah = 'yada'

def foo(bar):
    global blah
    print(blah, bar)
    
foo('test') # output: yada test

然而在这个例子中,如果全局变量没有事先定义(我把它注释掉),它会得到与您相同的错误:

#blah = 'yada'

def foo(bar):
    global blah
    print(blah, bar)
    
foo('test') # output: NameError: name 'blah' is not defined

所以,为了避免错误,你必须事先给你的全局变量一些值,比如 None .虽然如果你使用一个类来保存你需要的值,你可能会完全避免全局变量,比如:

import numpy as np

class MyClass(object):
    def __init__(self):
        #you'll have to set the numerical values to something that causes num_var_list to not loop infinitely
        self.number_list = None
        self.number_exit = 0
        self.number_target = 0
        self.price_buy = 0

    # This function generates a list of numbers under certain rules
    def num_var_list(self):
        self.number_list = []
        self.number_target = self.number_exit
        num_max_robot = (self.number_target * 20) / 100
        while num_max_robot > 0:
            num_robot = np.random.randint(1,int(num_max_robot))
            if num_robot > self.number_target:
                    self.number_list.append(self.number_target)
            else: 
                self.number_list.append(num_robot)
            self.number_target = self.number_target - self.number_target
        return self.number_list
            
    # This function generates a random number between a certain range
    def fun_price_buy(self):
        self.price_buy = np.random.randint(50000,300000)
        return self.price_buy

    # This function generates a random number between a certain range
    def fun_mx_buy(self):
        self.number_exit = np.random.randint(50, 150)
        return self.number_exit

def main():
    lista_number_list = []
    lista_price_buy = []
    lista_mx_buy = []
    
    my_class_instance = MyClass()

    # This loop append each function 50 times to a new list
    while len(lista_price_buy) <= 50: 
        lista_number_list.append(my_class_instance.num_var_list())
        lista_price_buy.append(my_class_instance.fun_price_buy())
        lista_mx_buy.append(my_class_instance.fun_mx_buy())

if __name__ == '__main__':
    main()
cyau
Reply   •   2 楼
cyau    3 年前

如果你仍然想使用全局变量(正如其他答案所指出的,不是推荐的方法),你必须在使用它们之前给它们一个值:

number_exit = 0
# This function generates a list of numbers under certain rules
def num_var_list():
    global number_list, number_exit, number_target
    number_list = []

你可以实例化 number_exit 也在函数的范围内,但在实际使用它之前需要这样做。

# This function generates a list of numbers under certain rules
def num_var_list():
    global number_list, number_exit, number_target
    number_list = []
    number_exit = 0
grantslape
Reply   •   3 楼
grantslape    3 年前

看起来您是通过函数中的全局变量定义变量的。你会想要转换你的 price_buy number_exit 到局部变量。

或者:

# This function generates a random number between a certain range
def fun_price_buy():
    return np.random.randint(50000,300000)

# This function generates a random number between a certain range
def fun_mx_buy():
    return np.random.randint(50, 150)
kağan hazal koçdemir
Reply   •   4 楼
kağan hazal koçdemir    3 年前

为什么你有这么多的全球业务?

def num_var_list():
    number_exit=fun_mx_buy()
    number_list = []
    number_target = number_exit
    num_max_robot = (number_target * 20) / 100
    while num_max_robot > 0:
        num_robot = np.random.randint(1, int(num_max_robot))
        if num_robot > number_target:
            number_list.append(number_target)
        else:
            number_list.append(num_robot)
        number_target = number_target - number_target
    return number_list

对你有用吗?

azro
Reply   •   5 楼
azro    3 年前

什么时候做 global price_buy 这意味着您使用全局定义的 price_buy 在方法中本地定义,但

  • 也不 购买价格 也没有 number_exit 全局定义(在方法之外)
  • 你不需要全局变量

它们只是本地的,而且更好:内联的

def fun_price_buy():
    price_buy = np.random.randint(50000,300000)
    return price_buy

# inline, no temporaty variable is needed
def fun_price_buy():
    return np.random.randint(50000,300000)

最后,如果您想从变量中的方法中获取值,以便对其进行操作:

import numpy as np

# This function generates a list of numbers under certain rules
def num_var_list(number_exit):
    number_list = []
    number_target = number_exit
    num_max_robot = (number_target * 20) / 100
    while num_max_robot > 0:
        num_robot = np.random.randint(1,int(num_max_robot))
        if num_robot > number_target:
                number_list.append(number_target)
        else: 
            number_list.append(num_robot)
        number_target = number_target - number_target
    return number_list
        
def fun_price_buy():
    return np.random.randint(50000,300000)

def fun_mx_buy():
    return np.random.randint(50, 150)

lista_number_list = []
lista_price_buy = []
lista_mx_buy = []

# This loop append each function 50 times to a new list
while len(lista_price_buy) <= 50: 
    number_exit = fun_mx_buy()
    price_buy = fun_price_buy()
    vr_list = num_var_list(number_exit)
   
    lista_number_list.append(vr_list)
    lista_price_buy.append(price_buy )
    lista_mx_buy.append(number_exit )