变量在函数外初始化时被赋值时出现了UnboundLocalError

2024-09-30 22:10:11 发布

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

我正在尝试向代码中添加python函数,但这样做时会出现UnboundLocalError:

Traceback (most recent call last):

File "/Users/name/Documents/project.py", line 44, in logic(coinType, 3.56, bagWeight, 356, 0.01)

File "/Users/name/Documents/project.py", line 14, in logic valueAddedCoins += value UnboundLocalError: local variable 'valueAddedCoins' referenced before assignment

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


Tags: ofintxtifvaluediffcoinprint
2条回答

变量valueaddCoins不在函数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

但这通常被认为是非常糟糕的做法,因为这样的代码通常很难调试(因为很难找出这些全局变量是在哪里修改的,bug是从哪里来的)

另一种方法是传入并返回修改后的值,如下所示:

def increment_int(valueAddedCoins):
    return valueAddedCoins += 1

valueAddedCoins = increment_int(valueAddedCoins)

这样你就会知道是什么修改了你的变量等

您可以添加

global valueAddedCoins

后定义函数

相关问题 更多 >