variable assignment within a loop

Dave Kuhlman dkuhlman at rexx.com
Mon Nov 3 16:33:44 EST 2003


hokieghal99 wrote:

> I 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.

Assigning a value to a new variable creates the variable.

If the body of your loop is executed zero times, then newdir will
not be assigned a value, and the variable newdir will not exist.

In general, if a variable is created and initialized in a loop, it
is a good idea to initialize the variable *before* the loop.

Something like the following might work for you:

    newdir = dir
    for bad_dir_char in bad_dir_chars:
        newdir = newdir.replace(bad_dir_char,'-')

You can find a little additional information about variables in
Python in the Python Programming FAQ, "2.2   What are the rules
for local and global variables in Python?":

http://www.python.org/doc/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

Note also that there are other ways to solve your problem.
Consider the following:

    >>> import string
    >>> bad_dir_chars = '*$@'
    >>> table = string.maketrans(bad_dir_chars, '-' * len(bad_dir_chars))
    >>> dir = '/abc/e*f/g$$'
    >>> newdir = string.translate(dir, table)
    >>> newdir
    '/abc/e-f/g--'


See the string module for information on maketrans() and
translate.

    http://www.python.org/doc/current/lib/module-string.html

[snip]

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dkuhlman at rexx.com




More information about the Python-list mailing list