[Tutor] design advice for function
Brian van den Broek
broek at cc.umanitoba.ca
Sun Dec 18 10:11:23 CET 2005
Christopher Spears said unto the world upon 2005-12-18 01:30:
> I got my function to work! It takes arguments and
> adds them:
Hi Christopher,
great!
> def adder(**args):
> argsList = args.values()
> sum = argsList[0]
> for x in argsList[1:]:
> sum = sum + x
> return sum
>
> print adder()
> print "---"
> print adder(a=5)
> print "---"
> print adder(a=5,b=6)
> print "---"
> print adder(a=5,b=6,c=7)
> print "---"
> print adder(ugly=7, good=6, bad=5)
> print "---"
>
> However, if I run the above code. I get an error:
>
> Traceback (most recent call last):
> File "C:\Documents and Settings\Christopher
> Spears\My
> Documents\programming\PythonScripts\Part4\Ex04\adder.py",
> line 8, in -toplevel-
> print adder()
> File "C:\Documents and Settings\Christopher
> Spears\My
> Documents\programming\PythonScripts\Part4\Ex04\adder.py",
> line 3, in adder
> sum = argsList[0]
> IndexError: list index out of range
>
> This is caused by the line: print adder(). Obviously
> if adder() doesn't receive any arguments, it can't
> build the lists resulting in an IndexError.
Right. You are also going to have a like problem with the next chunk
of you function:
for x in argsList[1:]:
sum = sum + x
(If you fix the adder() problem alone, you will still have a
adder(one_arg) problem.)
> What is
> the best way to solve this? Should I write some
> syntax into the function to check for arguments?
> Should I just write a seperate function to check for arguments?
Well, what you like adder() to do?
It is not uncommon for operations of a sequence to have a separate
clause for the special case of the empty sequence. So, you could do:
if not argsList:
return what_Christopher_wants
If you do that, can you think of a way to get around the
adder(one_arg) problem? Hint: do you really need to treat the first
element of argsList as a special case?
Have a think, and if you get stuck, post again.
Best,
Brian vdB
More information about the Tutor
mailing list