Newbie question...

Treutwein Guido Guido.Treutwein at nbg.siemens.de
Wed Sep 27 16:13:36 CEST 2000


>
> def adder(**args):
>
>     for x in args.keys():
>         y=y+x
>     return y
>
> print adder(good=1, bad=2, ugly=3)
> print adder(good="a", bad="b", ugly="c")
>
> Traceback (most recent call last):
>   File "C:\Python16\Pythonwin\pywin\framework\scriptutils.py", line
> 301, in RunScript
>     exec codeObject in __main__.__dict__
>   File "C:\Python16\examples\lpython\sol\CH4EX4.PY", line 8, in ?
>     print adder(good=1, bad=2, ugly=3)
>   File "C:\Python16\examples\lpython\sol\CH4EX4.PY", line 4, in adder
>     y=y+x
> UnboundLocalError: y

The problem is, that you don't initialise y.
Its further complicated by the fact, that you can't initialise it simply,
because you dont yet now, what the type is. (I'd assume, that this
intelligence wasn't really asked for in the exercise, to add or to
concatenate).

def adder(**args):
    for x in args.values(): # values is simpler than keys()
        try:
            y=y+x
        except UnboundLocalError:
            y=x
    return y

print adder(good=1, bad=2, ugly=3)
print adder(good="a", bad="b", ugly="c")





More information about the Python-list mailing list