variable assignment within a loop

Michael T. Babcock mbabcock at fibrespeed.net
Mon Nov 3 16:49:17 EST 2003


 
>  have this for loop in a program that I'm writing:
>
>         for bad_dir_char in bad_dir_chars:
>             newdir = dir.replace(bad_dir_char,'-')
>
> Now, when I use this if statement:
>
>         if newdir != dir:
>             old_dir_path = os.path.join(root,dir)
>             new_dir_path = os.path.join(root,newdir)
>             os.rename(old_dir_path,new_dir_path)
>             print "replaced:    ",bad_dir_char,"
>
> I get a "local variable 'newdir' referenced before assignment" error. 


The problem I would guess is that you don't create "newdir" before that 
loop.  It helps to have a shorter example:

a = ""
for x in "abc":
    a = x
    print a
print a

You'll get something like:
a
b
c
c

... because you've overwritten your "a" variable with each looping, when 
you're done the loop the 'a' variable still has the same value as it did 
in the last loop ("c").  Now, if you remove the 'a = ""' at the 
beginning, you'll get an error on that last "print a" because the 
variable doesn't exist in that "scope".  For the sake of visualization, 
scope is basically the depth of indentation in Python.  So if you didn't 
define the variable at this indent level or higher, it doesn't exist.

I'm not sure that is readable, but its what I had after a long day of 
C++/MFC coding ... ugh.

-- 
Michael T. Babcock
C.T.O., FibreSpeed Ltd.
http://www.fibrespeed.net/~mbabcock







More information about the Python-list mailing list