String
String

Reputation: 165

Python 3: "Local Variable referenced before assignment"

already looked at other answers and can't seem to fix this.

Here's my full code: http://pastebin.com/tW1kntG3

The code in question lies around here:

#Define the variables
global currentLoc
currentLoc=0

(The part that is breaking the code, apparently, is line 37.)

if call=="move":
    print("Move where?")
    print("")
    if currentLoc==0:
        print("Left: You cannot move left.")
        print("Right: " + locName[currentLoc+1])
    elif currentLoc>1:
        print("Left: " + locName[currentLoc-1])
        print("Right: " + locName[currentLoc+1])
    print("")
    print("Move left or right? Enter your choice.")
    direction = input("?: ")
    if direction=="left":
        print("Moved left.")
        if currentLoc>1:
            currentLoc = currentLoc-1
            pass
    elif direction=="right":
        currentLoc = currentLoc+1
        pass
pass

My error:

if currentLoc==0:
UnboundLocalError: local variable 'currentLoc' referenced before assignment

Upvotes: 0

Views: 4906

Answers (2)

Jasper
Jasper

Reputation: 3947

The global keyword introduces a global variable in a function's scope, it does not declare it as global for the whole program. You have to use global var_name in the function where you want to access the var_name variable.

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121406

You need to declare a global in the function. Python determines name scope per scope. If you assign to a name in a function (or use it as an import target, or a for target, or an argument, etc.) then Python makes that name a local unless stated otherwise.

As such, using global at the global level is rather pointless, because Python already knows it is a global there.

Add your global statement into each of function that tries to alter the name:

def displayMessage(call):
    global currentLoc

Upvotes: 1

Related Questions