[Tutor] design advice for function
Alan Gauld
alan.gauld at freenet.co.uk
Sun Dec 18 15:53:58 CET 2005
> def adder(**args):
> argsList = args.values()
> sum = argsList[0]
> for x in argsList[1:]:
> sum = sum + x
> return sum
> 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?
The Pythonic way is to use exceptions.
You can either handle the exception inside the function
or outside:
def adder(**args):
try:
# your code hee
except IndexError:
return 0 # or some other default, perhaps even None?!
OR
def adder(**args):
try:
# your code hee
except IndexError:
raise
try:
print adder()
print addre(a=1)
# etc...
except IndexError:
print 'oops, no arguments to adder'
In this case I'd probably use the first approach (with None as default),
but its up to you...
Alan G
More information about the Tutor
mailing list