-1

I am making a small python text based game, and Im having an issue with the global variable assignment. Heres the code in question.

print("story text removed for length")
light = False
killer_location =2
wolves = True;
commands = ["n", "S", "E", "W", "north", "south", "east", "west", "look","use","pick up", "attack","jump","throw"]
inventory = ["testinventoryobjectforarray"]
user_input = ">"
def forestscene():
    print("You are in a small clearing in the woods. Tall trees in every direction.")
    print("You see a dirt road to the north of you. ")
    
    while user_input not in commands:
        print("...")
        user_input = input("> ")
        if user_input.lower() == "n" or user_input.lower() == "north":
            roadscene()
        elif user_input.lower() == "s" or user_input.lower() == "south":
            wolfscene()
        elif user_input.lower() == "e" or user_input.lower() == "east":
            print("The trees are too dense and it's too dark to proceed further east.") 
     

forestscene()

However upon running, each function call returns "local variable User_Input referenced before assignment". I've tried adding global user_input, however that only resolved the first line, and adding them to all the calls causes the code to end after the first user input. Please help.

KniteRite
  • 11
  • 4

2 Answers2

0

This is one of python trap - unintuitive scope resolution. Look at this examples

b = False

def f():
    if b:
        print("True")
        # b = True

f()

It works as expected and nothing is printed. But if we uncomment b = True we get UnboundLocalError: local variable 'b' referenced before assignment.

What happened? When python cannot find variable in local scope it search it in global one. That's why in first example it just checks value of global b. When python enters the function it parses the funcion searching for local variables inside (even if its unaccessible branch). That is why in second program it puts b into locals, but have no value yet. When we try to access b we get above exception.

To fix your program, put user_input into def function. Then it will become local

kosciej16
  • 6,294
  • 1
  • 18
  • 29
0

Either put your user_input definition inside your function as a local variable or write global user_input at the start of your function to tell python to always use the global variable.

Cookiscuit
  • 21
  • 5