Search code examples
python-3.xglobal-variableslocal-variables

Confusing UnboundLocalError in Python 3.8


I am just starting to learn how to code so I hope I'm asking this correctly. For practice, I wanted to create a program that will print out classes since the form doesn't really change. It would take inputs, modify them, then put them in the correct order.

I'm having trouble taking the words from a list and remove spaces, adding underscores, and modifying values. In a function above the following code, I get the inputs and put them into a global list called required. I have messed with putting global required under def modify(): but that doesn't change anything. The commented out lines are the ones that keep flagging the error "UnboundLocalError: local variable 'i' referenced before assignment". I want to replace the original word and add a modified word. I've tried moving the indentation around without success.

It doesn't make sense to me as earlier in the code it has no problem printing 'i' and later in the code it has no trouble doing what I'm looking for either. Why is it having trouble with 'i' in the section in-between where it works just fine?

For reference, I am using the values of 'first name', 'last name', 'city', 'company name', 'town'. It prints the results for the strings with spaces correctly and modifies the single word strings and places them correctly into the list.

def modify():
    
    for i in range(0,len(required)+1):
        print()
        print(i)
        print()
        if chr(32) in str(required[i]):
            
            no_space = ""
            underscore = ""
            
            for l in str(required[i]):
            
                if ord(l) !=32:
                    
                    no_space += l
                    underscore += l
                
                elif ord(l) == 32:
                    
                    del i
                    underscore += "_"
                    
            
            print()
            print(no_space)
            print(underscore)
            # required.index[c] = no_space
            # required.append(underscore)
        
            # required.insert(i+1,underscore)
            # required[i] = no_space  
                      
                            
        elif chr(32) not in str(required[i]):
            
            if chr(95) in str(required[i]):
                continue
            
            elif chr(95) not in str(required[i]):
            
                additional = "the_" + str(required[i])
            
                required.insert(i+1,additional)
            
    print()
    for t in range(len(required)):
        print(str(t+1)+". "+required[t])

Thank you! I hope this isn't too confusing!


Solution

  • I think the error is cause by this line:

    del i
    

    You're deleting the value assigned to i in that specific moment, that's why at the beginning you can print it but after that it throws the exception.