On Sun, Dec 25, 2011 at 5:18 AM, daedae11 <daeda...@126.com> wrote:
> The following program has an error :
>                                           new += lists[int(j)]+"-";
> UnboundLocalError: local variable 'new' referenced before assignment
>
> But when I put the sentence  " new = '' " in the main() function, the
> program run normally.
>
> Please tell me why?  Isn't variable new in the following program is a global
> variable?
>
> the program is:
> lists = ['zero','one','two','three','four','five','six','seven','eight','nine'];
> new = "";

This new is global to your file.  Within your main() function you can
read the value  of new.

But inside main() you are creating another variable also called new
when you do this:
    new += .....

Your code is trying to add something to a variable that doesn't yet
have a value.  'new' is
a name that is not bound to any value.

You can either move the stuff at the top of your program into main, or
you could pass the outer new
into main as a parameter:    main(new):


>
>
> def main():
>
>     while True:
>         try:
>             iput = int(raw_input('Please input a int(0~1000): '))
>             if not 0<=iput<=1000:
>                 continue
>         except:
>             continue
>         break
>
>     iput = str(iput)
>     for j in iput:
>         new += lists[int(j)]+"-";
>     print new[0:-1];
>
> if __name__ == "__main__":
>     main();
>
> ________________________________
> daedae11
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to