[当我使用try/except
时,会得到KeyError
,但是当我不使用try
时,它会按预期工作。我敢肯定这是一个简单的修复程序,但是到目前为止,我已经花了一个多小时来解决这个问题,感谢您的帮助。这是代码,请原谅简单!
def return_book():
"""Return a book to the library"""
print("To return the book, you will need the ISBN")
isbn = str(input("Please enter the book's ISBN: "))
amount = input("How many books are you returning? ")
try:
isbn = int(isbn)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
try:
amount = int(amount)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
library[isbn][2] = library[isbn][2] + int(amount)
print(library)
当我们尝试从不存在的字典访问键时,发生了KeyError,您正在将字符串转换为整数并将该整数用作键!使用str(isbn)再次使isbn成为字符串:
try:
isbn = int(isbn)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
try:
amount = int(amount)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
library[str(isbn)][2] = library[str(isbn)][2] + int(amount)
print(library)