0

I am writing a test function to test a section of code before putting it into the file. This is just a sample. I've declared the variable 'map' at the top along with several others. When I run this code it gives me the variable called before definition error.

I can pas 'map' into the function and it works fine but this shouldn't be the case since 'map' is a global variable right? 'dict' works just fine. I thought maybe it was because I was assigning 'map = whatever' in the code but I rewrote it to include 'remap = map + 100' and it still flag 'map' as not being a legitimate variable to call. It's gotta be something simple but I'm not seeing it.

Note: converting 'map' to a string and formatting it with a leading zero is just a personal preference to make other parts of the code more user reader-friendly.

map = 101
dict = {'0302' : 'Hello.', '0202' : 'Hi.', '0201' :'Sup.'}

def test():
    
    while 1 > 0:
        
        choice = input('Add a number.')
        if choice == '1':
            map = map + 100
            map = str(format(map, '04d'))
        elif choice == '2':
            map = map + 1
            map = str(format(map, '04d'))          
        else:
            test()    
        
        if map in dict:
            print(dict[map])
         
        else:
            pass
            
        print(map)
        map = int(map)

test()
  • 4
    `map` and `dict` is a built-in functions do not use them as a variable names. – It_is_Chris Feb 09 '23 at 15:39
  • 1
    It does not cause the reported problem, but it [can cause other problems](/q/6039605); so please do not use `dict` or `map` as your variable names. As for the error, please see the linked duplicate. – Karl Knechtel Feb 09 '23 at 15:42
  • That was it! Declare it a Global in the first line of the function. Didn't realize Python was creating a local variable in that way. Thanks! – Michael Jason Stokes Feb 09 '23 at 16:03
  • @MichaelJasonStokes Try to avoid using `global` because you get unmanageable and inflexible code over time. Use parameters and a return value instead. – Matthias Feb 09 '23 at 16:06

0 Answers0