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)
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.