gpt4 book ai didi

python - NameError:名称 'x' 未定义 Python

转载 作者:行者123 更新时间:2023-12-05 09:05:40 25 4
gpt4 key购买 nike

我正在尝试解决此错误,但找不到解决方案。实际上,这段代码在一段时间内运行良好,但突然开始出现错误:

"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 没有删除错误时,代码完全符合我的要求。所以我不确定如何调整它以让它在没有 NameError 警告的情况下工作。

任何帮助将不胜感激。谢谢!

最佳答案

当执行 global price_buy 时,这意味着您使用全局定义的 price_buy 在您的方法中本地定义,但是

  • price_buynumber_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 )

关于python - NameError:名称 'x' 未定义 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66923625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com