[英]What did I do wrong in my function involving raising an exception?
說明:編寫一個函數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('增加六個3')->引發InvalidCommand()
這是我的代碼:
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)
有多個錯誤,因此我將在標題中解決這個問題:引發異常的錯誤是什么?
要引發異常,請使用raise ExceptionType(parameter)
,而不要return
像這樣:
class InvalidCommand(Exception):
pass
try:
s = raw_input("Enter a number:")
x = float(s)
except ValueError:
raise InvalidCommand(s+" is not a number")
請注意,始終需要在某個位置定義自定義異常類型。 由於InvalidCommand
是自定義的Exception類型(Python中未包含),因此在使用InvalidCommand
之前應為其定義類。 這個類定義可以放在python程序文件的頂部附近,只需要出現一次即可。
有關更多信息,請參見Python文檔-錯誤和異常
第37行(用於循環),您是立即從floats
追加值,這導致它將float列表兩次追加到output
變量。 對於輸入mul 5 6
,它正在返回('mul', [5.0, 6.0], [5.0, 6.0])
,因此要做的第一件事是在循環后放置output.append(floats)
。
for x in strdigits:
try:
float(x)
floats.append(float(x))
except ValueError:
return InvalidCommand(ValueError)
output.append(floats)
其次,這是錯誤的做法,
x == 'add' or 'sub' or 'mul' or 'div'
從Python shell檢查這些輸出。
>>> x = 'fas'
>>> x == 'add' or 'sub' or 'mul' or 'div'
'sub'
>>> x in ['add','sub','mul','div']
False
>>> bool('sub')
True
我希望一切都清楚了,所以將您的狀況更改為
if x in ['add','sub','mul','div']:
output.append(x)
else:
raise InvalidCommand(ValueError)
處理無效的command
值。
如Paul在評論中所建議,請使用raise Exception
引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.