why am i getting a traceback on this? from string import * instances = 0 def countSubStringMatch(target, key): for index in target: target.find("key") if index == key: instances += 1 m = "whateverman" countSubStringMatch(m, 'a')
btw im trying to create a function that finds an instance in a string, here's the error message: Traceback (most recent call last): File "C:/Python27/demo2.py", line 11, in <module> countSubStringMatch(m, 'a') File "C:/Python27/demo2.py", line 8, in countSubStringMatch instances += 1 UnboundLocalError: local variable 'instances' referenced before assignment
pretty sure that this: UnboundLocalError: local variable 'instances' referenced before assignment means you can't perform an operation (+, -, *, / ....) on a variable until you have assigned something to it. in your case you assigned 0 to instances outside of the function - it is a global variable. the instances that is 'inside' the function is a new variable that has local scope in the function. if you add "global instances" as the first line of your function it should work. look at the documentation of the global statement. it's kinda important to understand this. hope that made some sort of sense. unfortunately i can't come up with any really good reference right now. a google search of 'python variable scope' has some good results http://stackoverflow.com/questions/370357/python-variable-scope-question
when i put global in front of instances in the function i get a syntax error highlighting the = sign in the function where instances += 1... which again i don't know whats wrong with that lol
oh okay it works if i put global instances at the top of the function and then later have the statement instances += 1
that statement is telling the function to use the variable instances that was defined globally, i.e. outside of any functions.
yeah i changed all that though and put instances in the function but above the for loop so it wasn't global but it would still collect the instances
I found a pretty concise answer, in the documents of course, about the 4th paragraph down in this: http://docs.python.org/tutorial/controlflow.html#defining-functions
Join our real-time social learning platform and learn together with your friends!