1 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果您的引導(dǎo)不是列表中的第一個(gè),則您將落入 elif 并返回錯(cuò)誤消息
這可能有效:
def cib(id , library_collections):
for i in library_collections["books"]:
if id == i["ID"]:
i["Available"]=i["Available"]+1
return 'Item has successfully Been Checked In'
return 'Please restart the program and enter a valid ID'
因此,您首先遍歷所有書籍,如果找不到該書籍,您將返回錯(cuò)誤消息。
cob方法中的相同內(nèi)容
循環(huán)遍歷字典列表不是有效的方法。如果我正在編寫類似的代碼并且由于某種原因我無(wú)法使用正確的數(shù)據(jù)庫(kù),我會(huì)將 CSV 解析為 dict。數(shù)據(jù)模型可能是這樣的:
{ 1: {"available": 10, "name": "Hamlet", "author": "W. Shakespeare", "year": 1609},
123: {"available": 0, "name": "Война и мир", "author": "L. Tolstoi", "year": 1869},
}
其中 1 和 123 是 ID。您也可以將字符串用作 id。然后你簡(jiǎn)單地做你的方法
def cib(id, library_collection):
try:
library_collection[id]["available"] += 1
return 'Item has successfully Been Checked In'
except:
return 'Please restart the program and enter a valid ID'
或者
def cib(id, library_collection):
if id in library_collection:
library_collection[id]["available"] += 1
return 'Item has successfully Been Checked In'
else:
return 'Please restart the program and enter a valid ID'
避免 for 循環(huán)總是好主意。
添加回答
舉報(bào)