我的功能涉及提出异常,我做错了什么? [英] What did I do wrong in my function involving raising an exception?

查看:880
本文介绍了我的功能涉及提出异常,我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:
编写一个函数validate_input(string),它以'command arg1 arg2'格式接收一个命令字符串,并返回对('command',[arg1,arg2 ]),其中arg1和arg2已经被转换为浮点数。如果命令不是'add','sub','mul'或'div'之一,那么它必须引发InvalidCommand。如果参数无法转换为浮点数,则必须提高InvalidCommand。



典型输入和输出:



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



validate_input('hahahaha 2 3') - >引发InvalidCommand()



validate_input('add six 3') - >提升InvalidCommand()



这是我的代码: / p>

  class InvalidCommand(Exception):
pass

def validate_input(string):

validate_input(str) - >(str,[float])

如果string是一个有效的命令,返回其名称和参数
如果string不是有效的命令,提高InvalidCommand

有效的命令:
添加xy
子xy
mul xy
div xy

参数x和y必须可以转换为float


inlist = string.split('')
commands = []
strdigits = [ ]
floats = []
output = []
for x in in列表:
如果x.isdigit():
strdigits.append(x)
else:
commands.append(x)
for x在命令中:
try:
x =='add'或'sub'或'mul'或'div'
output.append(x)
除了ValueError:
返回InvalidCommand(ValueError )
for x in strdigits:
try:
float(x)
floats.append(float(x))
output.append(floats)
除ValueError外:
返回InvalidCommand(ValueError)
返回元组(输出)


解决方案

行#37(for循环),您正在从 floatats 中立即附加该值,这会导致其附加列表浮动两次到输出变量。
对于输入 mul 5 6 ,它返回('mul',[5.0,6.0],[5.0,6.0]),所以你需要做的第一件事就是在循环之后把 output.append(float)



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$除了ValueError:
返回InvalidCommand(ValueError)
output.append(floatats)

其次这是错误的做法,

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

从Python shell检查这些输出。

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

我希望很清楚,所以改变你的条件

 如果['add','sub','mul','div']中的x:
输出.append(x)
else:
raise InvalidCommand(ValueError)

处理无效的命令值。



正如Paul在评论中所建议的,使用 raise Exception 引发异常。


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)

解决方案

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.

这篇关于我的功能涉及提出异常,我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆