Try循环引发KeyError

问题描述 投票:-1回答:1

[当我使用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)
python
1个回答
0
投票

当我们尝试从不存在的字典访问键时,发生了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)
© www.soinside.com 2019 - 2024. All rights reserved.