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

Python图书数据列表输出问题求助:无法按预期格式打印

图书数据列表打印问题及解决方案

问题背景

录入图书数据后无法正确打印出预期的列表格式,原代码存在数据存储逻辑错误和打印逻辑错误,需修正并理解背后的逻辑。

原录入代码

keepAsking = True
author = ""
booktitle = ""
purchaseprice = float()
sellprice = float()
stockcount = int()
margin = float()
bookList = []
priceList = []

while keepAsking == True :
    print("Enter Book Data: -")

    author = input("Author: ")
    if author == "" :
        print("Blank Entry")
    else :
        booktitle = input("Title: ")
        if booktitle == "" :
            print("Blank Entry")
        else :
            purchaseprice = input("Purchase Price: ")
            if purchaseprice == "" :
                print("Incorrect Value")
            else :
                sellprice = input("Sell Price: ")
                if sellprice == "" :
                    print("Incorrect Value")
                else :
                    bookList.append(author)
                    bookList.append(booktitle)
                    if purchaseprice > sellprice :
                        bookList.remove(author)
                        bookList.remove(booktitle)
                    else :
                        priceList.append(purchaseprice)
                        priceList.append(sellprice)
                        stockcount = input("In Stock: ")
                        if stockcount == "" :
                            print("Incorrect Value")
                        else :
                            priceList.append(stockcount)

                    
    margin = ((float(sellprice)-float(purchaseprice))/float(purchaseprice))*100
    marginround = round(margin,2)
    priceList.append(marginround)
                    
    checkContinue = True
    while checkContinue == True :
        continues = input("Continue? [y/n]")
        continuesLower = continues.lower()

        if continues == "y" :
            checkContinue = False

        if continues == "n" :
            checkContinue = False
            keepAsking = False

原打印代码(无输出)

for a in bookList :
    counter = 0
    while counter == len(bookList) :
        print(bookList[0] + bookList[1])
        print("Purchase Price: " + priceList[0] + "Sell Price: " + priceList[1] + "In Stock: " + priceList [2] + "Margin: " + priceList [3])

问题分析与修正方案

核心问题拆解

  1. 数据存储混乱:原代码把图书的作者、书名放到bookList,价格、库存放到priceList,两个列表没有明确对应关系,单本书的信息被拆分存储,遍历匹配时极易出错。
  2. 类型处理错误:输入的采购价、售价是字符串,直接用purchaseprice > sellprice是字符串字典序比较,不是数值比较,逻辑完全错误。
  3. 打印逻辑失效:while counter == len(bookList)的条件永远不成立(初始counter=0,只有列表为空时len=0才会执行,但空列表也无内容可打印),导致循环体完全不执行,自然无输出。

修正后的完整代码

# 初始化存储所有图书的列表,每个元素是一本图书的字典
books = []
keep_asking = True

while keep_asking:
    print("Enter Book Data: -")
    
    # 确保作者输入有效
    while True:
        author = input("Author: ").strip()
        if author:
            break
        print("Blank Entry, please enter again.")
    
    # 确保书名输入有效
    while True:
        title = input("Title: ").strip()
        if title:
            break
        print("Blank Entry, please enter again.")
    
    # 确保采购价是有效数字
    while True:
        try:
            purchase_price = float(input("Purchase Price: ").strip())
            break
        except ValueError:
            print("Incorrect Value, please enter a number.")
    
    # 确保售价是有效数字且不低于采购价
    while True:
        try:
            sell_price = float(input("Sell Price: ").strip())
            if sell_price >= purchase_price:
                break
            print("Sell price can't be lower than purchase price, please enter again.")
        except ValueError:
            print("Incorrect Value, please enter a number.")
    
    # 确保库存是有效整数
    while True:
        try:
            stock_count = int(input("In Stock: ").strip())
            break
        except ValueError:
            print("Incorrect Value, please enter an integer.")
    
    # 计算利润率
    margin = ((sell_price - purchase_price) / purchase_price) * 100
    margin_round = round(margin, 2)
    
    # 将当前图书的所有信息存入字典,再添加到列表
    book_info = {
        "author": author,
        "title": title,
        "purchase_price": purchase_price,
        "sell_price": sell_price,
        "stock_count": stock_count,
        "margin": margin_round
    }
    books.append(book_info)
    
    # 确认是否继续录入
    while True:
        continue_input = input("Continue? [y/n]").strip().lower()
        if continue_input in ["y", "n"]:
            break
        print("Please enter 'y' or 'n'.")
    
    if continue_input == "n":
        keep_asking = False

# 打印所有图书信息
print("\n--- Book List ---")
for idx, book in enumerate(books, 1):
    print(f"Book {idx}: {book['author']} - {book['title']}")
    print(f"  Purchase Price: ${book['purchase_price']:.2f}")
    print(f"  Sell Price: ${book['sell_price']:.2f}")
    print(f"  In Stock: {book['stock_count']}")
    print(f"  Margin: {book['margin']}%\n")

关键改进点讲解

  1. 数据结构优化:用列表+字典存储图书数据,每个字典包含单本书的所有字段,每添加一本图书就把完整字典加入列表,后续遍历和访问字段清晰直观,避免了多列表匹配的混乱。
  2. 输入校验增强:用while True循环配合try-except确保输入的数值类型正确,同时直接处理售价低于采购价的情况,避免无效数据存入。
  3. 打印逻辑简化:用enumerate遍历图书列表,逐个输出每本书的所有字段,格式清晰易读,完全解决原打印代码无输出的问题。
  4. 代码风格优化:使用下划线命名法(符合Python规范),变量名更具语义,逻辑分层更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:19:01