0

I've set up an accumulator algorithm, but I initialized the accumulator variable outside of the block of code (in this example: main() ) that contains the accumulator loop:

alphabet = ""

def main():
    # 97 - 122 are the ASCII codes for the lower case alphabet
    for i in range( 97, 123 ):
        alphabet += chr( i )
    print alphabet

main()

For some reason I get this:

UnboundLocalError: local variable 'alphabet' referenced before assignment

The Solution I found was to initialize the variable inside the same block as the loop.

def main():
    alphabet = ""

    # 97 - 122 are the ASCII codes for the lower case alphabet
    for i in range( 97, 123 ):
        alphabet += chr( i )
    print alphabet

main()

My Question is why is this necessary?

Am I right in generalizing the problem and assuming that I need to initialize the variable in the same block as the loop, or is my problem specific to this example?

Is there some trait of python that I'm missing?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Josie Thompson
  • 5,608
  • 1
  • 13
  • 24
  • Oh yeah, that's definitely the problem. I should've searched the error message itself before posting the question. Sorry for the duplicate! – Josie Thompson Aug 01 '15 at 00:07

1 Answers1

0

Think of this alphabet += chr( i ) as shorthand for alphabet = alphabet + chr( i ). You are attempting to add chr(i) to alphabet and the first time this executes alphabet does not exist yet.

Dominic Larkin
  • 1,184
  • 3
  • 10
  • 18
  • I understand the += symbol. What I don't understand is why alphabet doesn't exist yet. I thought I'd already initialized it. Oh wait, do I need to make it public? – Josie Thompson Aug 01 '15 at 00:06