python unboundLocalError:在assignmen之前引用了局部变量“HighestStockName”

2024-09-29 17:19:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序,但我的一个函数有问题。当我试图运行这个程序时,我得到以下关于unboundLocalError.的错误。有人能帮我修复这个错误吗?在

def GetSale(Names, Prices, Exposure):
HighestStock = 0
for Stock in Names:
    TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] * 
    Prices[Stock][0]) * Exposure[Stock][0]
    if (TotalProfit > HighestStock):
       HighestStock = TotalProfit        
       HighestStockName = Stock
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")

Tags: 函数in程序fornamesdef错误stock
2条回答

如果参数'Names'为None或空,或者if (TotalProfit > HighestStock)条件为false。。。在

print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")

将引发UnboundLocalError,因为HighestStockName在for循环的if块中被赋值。在

也许可以尝试初始化HighestStock = 0下面的值'HighestStockName'。。。在

^{pr2}$

或者只需捕获UnboundLocalError异常并从中找出要做的事情。。。在

def GetSale(Names, Prices, Exposure):    
        HighestStock = 0 
        for Stock in Names:            
            TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] * Prices[Stock][0]) *     Exposure[Stock][0]             
            if (TotalProfit > HighestStock):       
                HighestStock = TotalProfit     
                HighestStockName = Stock
        try:
            print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
        except UnboundLocalError, e:
            # Do something after catching the exception

考虑一下,如果TotalProfit的所有计算结果都为0或负数,则永远不会输入内部if块,因此,最高股票名从未被分配/定义。在

相关问题 更多 >

    热门问题