[Tutor] design advice for function
Christopher Spears
cspears2002 at yahoo.com
Sun Dec 18 08:30:17 CET 2005
I got my function to work! It takes arguments and
adds them:
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. 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?
More information about the Tutor
mailing list