You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python OOP开发图书馆管理系统遇ValueError错误求助

解决图书馆管理系统中的ValueError及其他潜在问题

1. 核心错误:ValueError: too many values to unpack (expected 2)

直接遍历字典self.bookdict时,默认只会迭代字典的键(字符串类型),你试图把单个字符串拆成key, value两个变量,自然触发报错。正确做法是使用字典的items()方法,同时获取键值对。

修正后的displaybook方法:

def displaybook(self):
    print(f"Booklist of {self.namelib}:\n")
    # 用items()获取键值对,而非直接遍历字典
    for key, value in self.bookdict.items():
        print(f"Name: {key}  ||------------||  Author: {value}")

2. 其他潜在问题修复

2.1 方法调用缺少必要参数

lendbook、addbook、returnbook都需要传入对应参数,主程序调用时需补充用户输入逻辑:

match userchocie:
    case 1:
        myLib.displaybook()
    case 2:
        user = input("Enter your name: ")
        book = input("Enter the book name you want to lend: ")
        myLib.lendbook(user, book)
    case 3:
        book = input("Enter the book name you want to donate: ")
        author = input("Enter the author name: ")
        myLib.addbook(book, author)
    case 4:
        book = input("Enter the book name you want to return: ")
        myLib.returnbook(book)

2.2 lendbook方法的字典键错误

原代码中用user作为lenddict的键,但lenddict的键是书名,值是用户名,需修正:

def lendbook(self, user, book):
    # 新增书籍存在性检查
    if book not in self.bookdict:
        print("This book is not available in our library")
        return
    if book not in self.lenddict.keys():
        self.lenddict.update({book:user})
        print("Booklist has been updated. You can take the book now")
    else:
        # 修正键为book
        print(f"Book is already being lent by {self.lenddict[book]}")

2.3 addbook方法调用实例方式错误

原代码直接用Library.displaybook()调用类方法,实际应通过实例self调用:

def addbook(self, book, author):
    self.bookdict.update({book:author})
    print("Book has been added to the booklist\n")
    # 使用实例调用方法
    self.displaybook()

2.4 returnbook方法使用未定义属性

原代码中不存在self.booklist,归还书籍需操作self.lenddict:

def returnbook(self, book):
    if book in self.lenddict:
        del self.lenddict[book]
        print("Book has been returned successfully")
    else:
        print("This book was not lent from our library")

3. 完整修正后的代码

class Library:
    def __init__(self, dictofbooks, library_name):
        self.bookdict = dictofbooks
        self.namelib = library_name
        self.lenddict = {}
        
    def displaybook(self):
        print(f"Booklist of {self.namelib}:\n")
        for key, value in self.bookdict.items():
            print(f"Name: {key}  ||------------||  Author: {value}") 
    
    def lendbook(self, user, book):
        if book not in self.bookdict:
            print("This book is not available in our library")
            return
        if book not in self.lenddict.keys():
            self.lenddict.update({book:user})
            print("Booklist has been updated. You can take the book now")
        else:
            print(f"Book is already being lent by {self.lenddict[book]}")
    
    def addbook(self, book, author):
        self.bookdict.update({book:author})
        print("Book has been added to the booklist\n")
        self.displaybook()
    
    def returnbook(self, book):
        if book in self.lenddict:
            del self.lenddict[book]
            print("Book has been returned successfully")
        else:
            print("This book was not lent from our library")
    
if __name__ == '__main__':
    dictofbooks = {"Computer Science C++ class XI":"Sumita Arora", "Simple Science Experiments":"Minerva Publications", "A Brief History of Time":"Stephen Hawking", "Awareness Science class VIII":"Lakhmir Singh and Manjit Kaur", "Foundation Science Physics class VIII":"Pearson", "Mathematics for class VIII":"R.S. Aggarwal"}
    
    myLib = Library(dictofbooks, "K. Anand Library")    
    
    while(True):
        print(f"\nWelcome to {myLib.namelib}. Enter your choice to continue:")
        print("1. Display Books")
        print("2. Lend Books")
        print("3. Donate Books")
        print("4. Return Books")
        print("5. Exit")
        
        try:
            userchocie = int(input("--> "))
        except ValueError:
            print("Please enter a valid number between 1-5")
            continue
        
        match userchocie:
            case 1:
                myLib.displaybook()
            case 2:
                user = input("Enter your name: ")
                book = input("Enter the book name you want to lend: ")
                myLib.lendbook(user, book)
            case 3:
                book = input("Enter the book name you want to donate: ")
                author = input("Enter the author name: ")
                myLib.addbook(book, author)
            case 4:
                book = input("Enter the book name you want to return: ")
                myLib.returnbook(book)
            case 5:
                print("Thank you for using our library!")
                break
            case _:
                print("Invalid choice, please enter a number between 1-5")

内容的提问来源于stack exchange,提问作者Krishna Anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:50:34