修复UnboundLocalError

时间:2018-07-11 07:29:59

标签: python

def main():
    cash = float(input("How much money: "))
    coins = 0

def changeCounter(n):
    while True:
        if cash - n > 0:
            cash -= n
            coins += 1
        else:
            break
    return

main()
changeCounter(0.25)

运行此代码时,出现错误

  

UnboundLocalError:分配前已引用局部变量'cash'

我该如何解决?

2 个答案:

答案 0 :(得分:2)

问题在于变量cashcoins仅存在于函数main的“作用域”中,即在changeCounter中不可见。试试:

def main():
    cash = float(input("How much money: "))
    coins = 0
    return cash, coins

def changeCounter(n, cash, coins):
    while True:
        if cash - n > 0:
            cash -= n
            coins += 1
        else:
            break
    # return
    return coins # presumably

cash, coins = main()
changeCounter(0.25, cash, coins)

答案 1 :(得分:1)

您需要将cashcoins定义为global variable

cash = 0
coins = 0

def main():
    global cash, coins

    cash = float(input("How much money: "))
    coins = 0

def changeCounter(n):
    global cash, coins

    while True:
        if cash - n > 0:
            cash -= n
            coins += 1
        else:
            break
    return

main()
changeCounter(0.25)
  

但是比将状态存储在全局变量中更好的方法是使用   重现变量和函数参数或其他方法。看到   Why are global variables evil?