What did I do wrong in my function involving raising an exception?

£可爱£侵袭症+ 提交于 2020-02-07 06:29:59

问题


The instructions: Write a function validate_input(string) which takes a command string in the format 'command arg1 arg2' and returns the pair ('command', [arg1, arg2]), where arg1 and arg2 have been converted to floats. If the command is not one of 'add', 'sub', 'mul', or 'div', it must raise InvalidCommand. If the arguments cannot be converted to floats, it must raise InvalidCommand.

Typical inputs and outputs:

validate_input('add 2 3') -> ('add' [2. , 3.])

validate_input('hahahaha 2 3') -> Raises InvalidCommand()

validate_input('add six 3') -> Raises InvalidCommand()

Here is my code:

class InvalidCommand(Exception):
    pass

def validate_input(string):
"""
validate_input(str) -> (str, [float])

If string is a valid command, return its name and arguments.
If string is not a valid command, raise InvalidCommand

Valid commands:
  add x y
  sub x y
  mul x y
  div x y

Arguments x and y must be convertable to float.

"""
    inlist = string.split(' ')
    commands = []
    strdigits = []
    floats = []
    output = []
    for x in inlist:
        if x.isdigit():
            strdigits.append(x)
        else:
            commands.append(x)
    for x in commands:
        try:
            x == 'add' or 'sub' or 'mul' or 'div'
            output.append(x)
        except ValueError:
            return InvalidCommand(ValueError)
    for x in strdigits:
        try:
            float(x)
            floats.append(float(x))
            output.append(floats)
        except ValueError:
            return InvalidCommand(ValueError)
    return tuple(output)

回答1:


Line #37 (for loop), You are appending the value immediately from floats, which is causing it to append the list of float twice to the output variable. For input mul 5 6, it is returning ('mul', [5.0, 6.0], [5.0, 6.0]), so the first thing you need to do it put output.append(floats) after the loop.

for x in strdigits:
    try:
        float(x)
        floats.append(float(x))
    except ValueError:
        return InvalidCommand(ValueError)
output.append(floats)

Secondly this is wrong way to do it,

x == 'add' or 'sub' or 'mul' or 'div'

Check these output from Python shell.

>>> x = 'fas'
>>> x == 'add' or 'sub' or 'mul' or 'div'
'sub'
>>> x in ['add','sub','mul','div']
False
>>> bool('sub')
True

I hope it's clear, so change your condition to

if x in ['add','sub','mul','div']:
    output.append(x)
else:
    raise InvalidCommand(ValueError)

to deal with invalid command value.

As Paul suggested in comments, use raise Exception to raise an exception.




回答2:


There are multiple errors,so I will address the question in the title: what are the errors with raising an exception ?

To raise an exception, use raise ExceptionType(parameter), not return

Like this:

 class InvalidCommand(Exception):
     pass

 try:
      s = raw_input("Enter a number:")
      x = float(s)
 except ValueError:
      raise InvalidCommand(s+" is not a number")

Note that Custom exception types always need to be defined somewhere. Since InvalidCommand is a custom Exception type (not included in Python), there should be a class definition for InvalidCommand before using it. This class definition could go near the top of the python program file, and only needs to appear once.

For more, see Python docs -- errors and exceptions



来源:https://stackoverflow.com/questions/32294214/what-did-i-do-wrong-in-my-function-involving-raising-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!