Python UnboundLocalError:分配前引用的局部变量“Core_prices”
我使用了一个函数计算服务器价格,因此我制作了一个函数,用于检索服务器组件的默认价格,并计算数据库中存在的每台服务器的服务器价格,但我尝试运行此函数,但出现以下错误:Python UnboundLocalError:分配前引用的局部变量“Core_prices”,python,Python,我使用了一个函数计算服务器价格,因此我制作了一个函数,用于检索服务器组件的默认价格,并计算数据库中存在的每台服务器的服务器价格,但我尝试运行此函数,但出现以下错误: function.py import MySQLdb def calculations_metric (param) : db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project") cursor = db.cursor() sql = "
function.py
import MySQLdb
def calculations_metric (param) :
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM examples_calculationsmetric"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
RAM_prices = int(row[1])
Core_prices = int(row[2])
HHD_SATA_prices =int(row[3])
HHD_SSD_prices =int(row[4])
CPU_priority = int(row[5])
Avaibility = int(row[6])
db.close()
db1 = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor1 = db1.cursor()
sql1 = "SELECT * FROM examples_servercomponents WHERE id ='%d'" %(param)
cursor1.execute(sql1)
results1 = cursor1.fetchall()
for row in results1:
if row[6] == 'SATA':
Core_price = int(row[2]) * Core_prices # the error is here
Priority_price = int(row[3]) * CPU_priority
RAM_price = int(row[4]) * RAM_prices
HDD_price = int(row[5]) * HHD_SATA_prices
Availibility_price = int(row[7])*Avaibility
elif row[6] == 'SSD':
Core_price = int(row[2]) * Core_prices
Priority_price = int(row[3]) * CPU_priority
RAM_price = int(row[4]) * RAM_prices
HDD_price = int(row[5]) * HHD_SSD_prices
Availibility_price = int(row[7])*Avaibility
price = Core_price + Priority_price + RAM_price + HDD_price + Availibility_price
db1.close()
return price
我不知道是什么错误,所以如果有人能帮助我,当你的SELECT*FROM examples\u Calculation Metric没有返回任何结果时,我会非常高兴,核心价格从未设置,循环中的其他变量也没有设置
Python名称在分配给之前不存在,因此,如果结果是空列表,则for循环中的名称永远不会分配给,因此在稍后循环results1时不存在
您可以设置这些名称的默认值作为解决方法:
RAM_prices = 0
Core_prices = 0
HHD_SATA_prices = 0
HHD_SSD_prices = 0
CPU_priority = 0
Avaibility = 0
至少要确保它们已定义。出于兴趣,为什么要连接到同一个数据库两次?为什么不为第二个查询重用第一个连接?错误是因为examples\u calculationsmetric表为空。那张桌子上没有一行。现在可以用了