0
我想返回KeyError
,但它會返回None
。我不懂爲什麼。我想返回KeyError not None
if index == self.length or self.slots[index]==None:
raise KeyError
我想返回KeyError
,但它會返回None
。我不懂爲什麼。我想返回KeyError not None
if index == self.length or self.slots[index]==None:
raise KeyError
你不提高一個KeyError
因爲你不進入if
分枝。而且您不輸入if
-分支,因爲您的條件都不是true
。
如果測試用例(你沒有顯示!)真的應該提高KeyError
,你可能需要調整你的條件。
要調試這個問題,你可以插入一些print
-statements:
print(index, self.length, index==self.length)
print(self.slots[index], self.slots[index]==None)
if index == self.length or self.slots[index]==None:
raise KeyError
或使用您選擇的調試器。
但是一些評論:
>=
的長度(包括==
!)。is
與None
進行比較。 None
和NotImplemented
保證單身。KeyError
使用異常消息,例如raise KeyError('index out of bounds or item is None! Try again.')
return
將返回None
。這可能就是爲什麼你的代碼返回None
!
@AndrewL''()'和消息是可選的,它也是「正確的」來引發異常類* shudder *。 – MSeifert
您是否知道「返回」KeyErrror和「引發」KeyError是非常不同的事情?從你發佈的內容來看,我不知道你是否在職,但是如果你不在某個職能上,你不能「返回」某些東西。您可能想要編輯您的問題,以提供更多關於您在此嘗試完成的詳細信息 –