1
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)

When I run this code, I get the error

UnboundLocalError: local variable 'cash' referenced before assignment

How can I fix this?

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
  • Possible duplicate of [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – pppery Sep 09 '19 at 22:05

2 Answers2

1

The problem is that the variables cash and coins live only in the "scope" of function main, i.e. are not visible in changeCounter. Try:

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)
minmax
  • 493
  • 3
  • 10
0

You need to define cash and coins as 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)

But better way than storing the state in global variables is using returing variables and function arguments or other method. See Why are global variables evil?

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91