0

I am trying to add a python function to my code, but when I do so I get an 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

Why am I getting an UnboundLocalError?

  • Possible duplicate of [How to change a variable after it is already defined in Python](https://stackoverflow.com/questions/41369408/how-to-change-a-variable-after-it-is-already-defined-in-python) – Patrick Haugh Apr 27 '18 at 15:34

2 Answers2

0

You can add

global valueAddedCoins

after definition function

AJackTi
  • 63
  • 2
  • 7
0

The variable valueAddedCoins is not in the scope of function logic see for example http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html on the topic

To be able to modify it you have to declare it as global inside of the function:

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

but this is often considered as very bad practice, because such code is usually hard to debug (because it's hard to find out where such global variables are modified, where the bugs are coming from)

the alternative approach is to pass it in and return it's modified value like this:

def increment_int(valueAddedCoins):
    return valueAddedCoins += 1

valueAddedCoins = increment_int(valueAddedCoins)

this way you will always know what modified your variable etc.

Bob
  • 5,809
  • 5
  • 36
  • 53