将值赋给变量初始化外部函数时的UnboundLocalError

时间:2018-04-27 15:27:53

标签: python

我正在尝试将python函数添加到我的代码中,但是当我这样做时,我得到一个UnboundLocalError:

  

追踪(最近一次呼叫最后一次):

     

文件“/Users/name/Documents/project.py”,第44行,in   逻辑(coinType,3.56,bagWeight,356,0.01)

     

文件“/Users/name/Documents/project.py”,第14行,逻辑       valueAddedCoins + = value UnboundLocalError:赋值前引用的局部变量'valueAddedCoins'

def logic(coin_txt, w1, wBag, cWeight, vCoin):
    diff = abs(wBag - cWeight)
    if diff == 0:
        print("Bag ok")
        return

    coins = diff / w1
    value = coins * vCoin

    if wBag < cWeight:
        valueAddedCoins += value
        print(int(coins), coin_txt, " coins missing")
        print(diff, "grams too little")
    else:
        valueRemovedCoins += value
        print(int(coins), coin_txt, " coins too many")
        print(diff, " grams too many")

valueAddedCoins = 0
valueRemovedCoins = 0
numBagsChecked = 0

continueChecking = True;
while continueChecking:

    #asking information about the coins and deducing wether or not the weight is correct
    bagWeight = float(input("Weight of bag of coins (no unit): "))
    coinType = input("Type of coins in bag: 1 pence or 2 pence?")

    numBagsChecked += 1

    if coinType == "1 pence":
        logic(coinType, 3.56, bagWeight, 356, 0.01)
    elif type_of_coin == "2 pence":
        logic(coinType, 7.12, bagWeight, 712, 0.02)

    check = input("Another bag? (Y/N): ")
    if check == "N":
        continueChecking = False

为什么我会收到UnboundLocalError?

2 个答案:

答案 0 :(得分:0)

您可以添加

global valueAddedCoins

定义后的功能

答案 1 :(得分:0)

变量valueAddedCoins不在函数logic的范围内 请参阅主题

上的http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

为了能够修改它,你必须在函数内声明它为global

def logic(coin_txt, w1, wBag, cWeight, vCoin):
    global valueAddedCoins
    valueAddedCoins += 1

但这通常被认为是非常糟糕的做法,因为这样的代码通常很难调试(因为很难找到修改这些全局变量的地方,这些错误来自哪里)

替代方法是将其传入并返回其修改后的值,如下所示:

def increment_int(valueAddedCoins):
    return valueAddedCoins += 1

valueAddedCoins = increment_int(valueAddedCoins)
通过这种方式,您将始终知道修改了您的变量等等。