Home > front end >  Handling a variable but bounded number of arguments
Handling a variable but bounded number of arguments

Time:04-06

Here is the code I was using:

def arithmetic_arranger(eq1 = '', eq2 = '', eq3 = '', eq4 = '', eq5 = '', answers = False):
try:
    print(eq1   eq2   eq3   eq4   eq5)
except TypeError:
    raise('Does not work')

arithmetic_arranger('hello', 'hola', 'konnichiwa', 'bonjour', 'hi', 'hey', 'sup')

I want to call the function, and if there are more than 5 arguments (excluding variables) then it should return (for my purposes) 'Does not work'. This is my first time dealing with exceptions, and I cannot seem to figure out how to deal with it coming from inside the function.

Tried:

def arithmetic_arranger(eq1 = '', eq2 = '', eq3 = '', eq4 = '', eq5 = '', answers = False):

try:
print(eq1   eq2   eq3   eq4   eq5)
except TypeError:
raise('Does not work')
arithmetic_arranger('hello', 'hola', 'konnichiwa', 'bonjour', 'hi', 'hey', 'sup')

Got:

TypeError: arithmetic_arranger() takes from 0 to 6 positional arguments but 7 were given

Expecting:

Does not work

CodePudding user response:

You can use *args to get a list of arguments, then check the length to see if it is > 5:

def arithmetic_arranger(*args, answers=False):
    if len(args) > 5:
        return "does not work"
# First is fine
>>> arithmetic_arranger('1', '2', '3', '4', '5')
# Second has 6 args; will not work
>>> arithmetic_arranger('1', '2', '3', '4', '5', '6')
'does not work'
# This is still 6 args; will not work
>>> arithmetic_arranger('1', '2', '3', '4', '5', True)
'does not work'
# This will work because you specified that the last arg is answers; not in *args
>>> arithmetic_arranger('1', '2', '3', '4', '5', answers=True)

Note the use of return, which sends the caller a value. I think you may have mistaken return for raise()?

A good read on *args and **kwargs

CodePudding user response:

You can use *args to handle a variable number of parameters, and then use ' '.join() in the print statement to handle cases when less than 5 parameters are passed in:

def arithmetic_arranger(*args):
    if len(args) > 5:
        raise TypeError('Can specify at most five arguments to arithmetic_arranger()')
    print(' '.join(args))
  • Related