Donald Lee
Donald Lee

Reputation: 11

Getting a traceback error and claims my variable is referenced before assignment

Getting a Traceback error, states dime is not referenced before assignment, and there's an error with my function. I've tried googling, but could not find an answer.

change = float(input("How much change will they recieve?:"))
nickel=1
def conclude():
    if change == 0.04 or change == 0.03:
        global nickel
        nickel = nickel + 1
        conclude()
        if nickel == 2:
            dime = dime + 1
            nickel = 0
            conclude()
        else:
            print("You owe a nickel")
            conclude()
    elif dime >= 1:
        print("You owe " + str(dime) + " dime(s)")
        conclude()
    else:
        print("Done")
conclude()

Input = 10

Output

How much change will they recieve?:10
Traceback (most recent call last):
  File "C:/Users/donal/PycharmProjects/ChangeCalculator/testv2.py", line 20, in <module>
    conclude()
  File "C:/Users/donal/PycharmProjects/ChangeCalculator/testv2.py", line 15, in conclude
    elif dime >= 1:
UnboundLocalError: local variable 'dime' referenced before assignment

Process finished with exit code 1

Upvotes: 0

Views: 60

Answers (1)

XPhyro
XPhyro

Reputation: 528

You cannot use an unassigned variable. In this case, on the lines

elif dime >= 1:
    ...str(dime)...

you are using the variable dime, without assigning something to it. Although you did not get an error on the line

dime = dime + 1

it also behaves the same way, which you can get by giving a different input.

What you should do is declare dime, and assign an initial value to it. You can do so like this:

def conclude():
    dime = 0
    [rest of the code]

Upvotes: 1

Related Questions