• + 44 comments

    After much banging of my head, I Googled "local variable referenced before assignment", because I kept getting the "UnboundLocalError: local variable 'age' referenced before assignment" error. One of the answers suggested I use 'global' for Python and it worked! The workaround is to pass a parameter instead of using the more dangerous 'global' keyword, but since we can't change the calling code, 'global' is the way to go. If someone solved this without using 'global' for Python3, please post your solution. It would be good to learn better ways.

    class Person:
        def __init__(self, initialAge):
            # Add some more code to run some checks on initialAge
            self.age = 0
            if initialAge < 0:
                print("Age is not valid, setting age to 0.")
            else:
                self.age = initialAge
    
    
        def amIOld(self):
            # Do some computations in here and print out the correct statement to the console
            if age < 13:
                print("You are young.")
            elif 13 <= age < 18:
                print("You are a teenager.")
            elif age >= 18:
                print("You are old.")
    
        def yearPasses(self):    
            # Increment the age of the person in here
            global age
            age += 1