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

Python POS系统代码运行报错求助:多功能模块代码排查

POS系统代码错误排查与修复方案

一、核心错误点及对应修复

1. 登录模块逻辑缺陷

原代码仅在首次循环前获取账号密码,后续重试不会更新输入值,导致三次验证共用初始输入。
修复:将输入语句移入循环内,每次重试重新获取账号密码:

def login():
    attempts = 0
    while attempts < 3:
        user_id = input("Please enter your User ID: ")
        password = input("Please enter your password: ")
        if user_id == "user" and password == "password":
            print("Login successful!")
            return True
        else:
            attempts += 1
            if attempts < 3:
                print("Incorrect credentials. Please try again.")
            else:
                print("Too many attempts. Access denied.")
                return False

2. 库存变量作用域错误

load_inventory函数未返回库存字典,也未声明全局变量,导致其他函数调用inventory时触发NameError。
修复:函数返回库存字典,主程序中加载后全局可用:

def load_inventory():
    inventory = {}
    # 用with语句自动关闭文件,避免资源泄漏
    with open("RetailStoreItemData.txt", "r") as file:
        for line in file:
            parts = line.strip().split(",")
            upc = parts[0]
            description = parts[1]
            # 将字符串类型的数值转为int/float
            item_max_qty = int(parts[2])
            order_threshold = int(parts[3])
            replenishment_order_qty = int(parts[4])
            item_on_hand = int(parts[5])
            unit_price = float(parts[6])
            order_placed = parts[7]
            item = Item(upc, description, item_max_qty, order_threshold, replenishment_order_qty, item_on_hand, unit_price, order_placed)
            inventory[upc] = item
    return inventory

# 主程序中新增库存加载逻辑
if login():
    inventory = load_inventory()
    while True:
        # 后续逻辑不变

3. Item类方法参数拼写错误

updateUnitOnHand方法参数numberOfltems中字母l与I混淆,应为numberOfItems,导致调用时传参失败。
修复:修正参数名并新增销量统计属性:

class Item:
    def __init__(self, upc, description, item_max_qty, order_threshold, replenishment_order_qty, item_on_hand, unit_price, order_placed):
        self.upc = upc
        self.description = description
        self.item_max_qty = item_max_qty
        self.order_threshold = order_threshold
        self.replenishment_order_qty = replenishment_order_qty
        self.item_on_hand = item_on_hand
        self.unit_price = unit_price
        self.order_placed = order_placed
        self.qty_sold = 0  # 新增销量统计属性
    
    def updateUnitOnHand(self, numberOfItems):
        self.item_on_hand += numberOfItems

4. 库存数据类型未转换

从文件读取的数值(如item_on_hand、unit_price)为字符串类型,直接参与运算会触发TypeError。
修复:在load_inventory中完成类型转换,见上述修复代码。

5. 退货函数遍历字典时修改的问题

returnAllitems直接遍历sale字典并修改其大小,会触发RuntimeError。
修复:将字典键转为列表后再遍历:

def returnAllitems(sale):
    for upc in list(sale.keys()):
        item = inventory[upc]
        item.updateUnitOnHand(sale[upc])
        item.qty_sold -= sale[upc]  # 同步扣减销量
    sale.clear()
    print("All items successfully returned.")

6. 销售报表逻辑错误

原代码用item_max_qty - item_on_hand计算销量,逻辑错误(max_qty是最大库存,不是初始库存)。
修复:通过Item类的qty_sold属性统计销量:

# newSale中新增销量累加逻辑
def newSale():
    sale = {}
    while True:
        upc = input("Please enter the UPC of the item you'd like to add to your sale. Enter 'done' when finished: ")
        if upc.lower() == "done":
            break
        if upc not in inventory:
            print("Invalid UPC. Please try again.")
            continue
        item = inventory[upc]
        if item.item_on_hand > 0:
            item.updateUnitOnHand(-1)
            item.qty_sold += 1
            if upc in sale:
                sale[upc] += 1
            else:
                sale[upc] = 1
        else:
            print("Sorry, we are currently out of stock on this item.")
    return sale

# 销售报表生成函数修改
def generateSalesReport():
    print("\nSALES REPORT\n")
    print("UPC\tDESCRIPTION\tUNIT PRICE\tQTY SOLD\n")
    total = 0
    has_sales = False
    for upc in inventory:
        item = inventory[upc]
        if item.qty_sold > 0:
            has_sales = True
            print(f"{item.upc}\t{item.description}\t{item.unit_price}\t{item.qty_sold}")
            total += item.qty_sold * item.unit_price
    if not has_sales:
        print("No sales recorded.")
    else:
        print(f"\nTotal Sales: {total:.2f}")

7. 主程序强制退货逻辑不合理

原代码不管支付成功与否都调用returnItem,不符合业务逻辑。
修复:改为用户可选退货,支付失败自动取消订单:

if option == "1":
    sale = newSale()
    if sale:
        if finalizeSale(sale):
            print("Thank you for your purchase!")
            return_choice = input("Would you like to return any items? (y/n): ")
            if return_choice.lower() == "y":
                while True:
                    return_opt = input("\n1. Return single item\n2. Return all items\n3. Done\nEnter option: ")
                    if return_opt == "1":
                        returnItem(sale)
                    elif return_opt == "2":
                        returnAllitems(sale)
                        break
                    elif return_opt == "3":
                        break
                    else:
                        print("Invalid option.")
        else:
            print("Canceling order, returning items to inventory.")
            returnAllitems(sale)

二、修复后完整代码

def login():
    attempts = 0
    while attempts < 3:
        user_id = input("Please enter your User ID: ")
        password = input("Please enter your password: ")
        if user_id == "user" and password == "password":
            print("Login successful!")
            return True
        else:
            attempts += 1
            if attempts < 3:
                print("Incorrect credentials. Please try again.")
            else:
                print("Too many attempts. Access denied.")
                return False

class Item:
    def __init__(self, upc, description, item_max_qty, order_threshold, replenishment_order_qty, item_on_hand, unit_price, order_placed):
        self.upc = upc
        self.description = description
        self.item_max_qty = item_max_qty
        self.order_threshold = order_threshold
        self.replenishment_order_qty = replenishment_order_qty
        self.item_on_hand = item_on_hand
        self.unit_price = unit_price
        self.order_placed = order_placed
        self.qty_sold = 0
    
    def updateUnitOnHand(self, numberOfItems):
        self.item_on_hand += numberOfItems

def load_inventory():
    inventory = {}
    try:
        with open("RetailStoreItemData.txt", "r") as file:
            for line in file:
                parts = line.strip().split(",")
                if len(parts) != 8:
                    print(f"Skipping invalid line: {line}")
                    continue
                upc = parts[0]
                description = parts[1]
                item_max_qty = int(parts[2])
                order_threshold = int(parts[3])
                replenishment_order_qty = int(parts[4])
                item_on_hand = int(parts[5])
                unit_price = float(parts[6])
                order_placed = parts[7].lower()
                item = Item(upc, description, item_max_qty, order_threshold, replenishment_order_qty, item_on_hand, unit_price, order_placed)
                inventory[upc] = item
        return inventory
    except FileNotFoundError:
        print("Error: RetailStoreItemData.txt not found.")
        return {}

def newSale():
    sale = {}
    while True:
        upc = input("Please enter the UPC of the item you'd like to add to your sale. Enter 'done' when finished: ")
        if upc.lower() == "done":
            break
        if upc not in inventory:
            print("Invalid UPC. Please try again.")
            continue
        item = inventory[upc]
        if item.item_on_hand > 0:
            item.updateUnitOnHand(-1)
            item.qty_sold += 1
            if upc in sale:
                sale[upc] += 1
            else:
                sale[upc] = 1
        else:
            print("Sorry, we are currently out of stock on this item.")
    return sale

def finalizeSale(sale):
    if not sale:
        print("No items in sale.")
        return False
    total = 0
    print("In Your sale:")
    for upc in sale:
        item = inventory[upc]
        price = item.unit_price * sale[upc]
        total += price
        print(f"{item.description}: {sale[upc]} × {item.unit_price} = {price:.2f}")
    print(f"Total: {total:.2f}\n")
    while True:
        try:
            cash = float(input("Please enter the amount of cash given: "))
            break
        except ValueError:
            print("Invalid input. Please enter a number.")
    if cash >= total:
        change = cash - total
        print(f"Change: {change:.2f}")
        return True
    else:
        print(f"Insufficient funds. Need {total - cash:.2f} more.")
        return False

def returnItem(sale):
    if not sale:
        print("No items to return.")
        return
    upc = input("Please enter the UPC of the item you'd like to return: ")
    if upc in sale:
        item = inventory[upc]
        item.updateUnitOnHand(1)
        item.qty_sold -= 1
        sale[upc] -= 1
        if sale[upc] == 0:
            del sale[upc]
        print("Item successfully returned.")
    else:
        print("This item is not in your sale.")

def returnAllitems(sale):
    if not sale:
        print("No items to return.")
        return
    for upc in list(sale.keys()):
        item = inventory[upc]
        item.updateUnitOnHand(sale[upc])
        item.qty_sold -= sale[upc]
    sale.clear()
    print("All items successfully returned.")

def generateInventoryReport():
    if not inventory:
        print("No inventory data available.")
        return
    print("\nINVENTORY REPORT\n")
    print(f"{'UPC':<10}{'DESCRIPTION':<20}{'MAX QTY':<10}{'ORDER THRESHOLD':<15}{'REPLENISH QTY':<15}{'ON HAND':<10}{'UNIT PRICE':<12}{'ORDER PLACED':<12}")
    print("-" * 100)
    for upc in inventory:
        item = inventory[upc]
        print(f"{item.upc:<10}{item.description:<20}{item.item_max_qty:<10}{item.order_threshold:<15}{item.replenishment_order_qty:<15}{item.item_on_hand:<10}{item.unit_price:<12.2f}{item.order_placed:<12}")

def generateSalesReport():
    if not inventory:
        print("No inventory data available.")
        return
    print("\nSALES REPORT\n")
    print(f"{'UPC':<10}{'DESCRIPTION':<20}{'UNIT PRICE':<12}{'QTY SOLD':<10}")
    print("-" * 60)
    total = 0
    has_sales = False
    for upc in inventory:
        item = inventory[upc]
        if item.qty_sold > 0:
            has_sales = True
            sale_total = item.qty_sold * item.unit_price
            total += sale_total
            print(f"{item.upc:<10}{item.description:<20}{item.unit_price:<12.2f}{item.qty_sold:<10}")
    if not has_sales:
        print("No sales recorded.")
    else:
        print("-" * 60)
        print(f"Total Sales: {total:.2f}")

if login():
    inventory = load_inventory()
    while True:
        option = input("\n1. Start a new sale\n2. Generate Inventory Report\n3. Generate Sales Report\n4. Quit\n\nPlease enter an option: ")
        if option == "1":
            sale = newSale()
            if sale:
                if finalizeSale(sale):
                    print("Thank you for your purchase!")
                    return_choice = input("Would you like to return any items? (y/n): ")
                    if return_choice.lower() == "y":
                        while True:
                            return_opt = input("\n1. Return single item\n2. Return all items\n3. Done\nEnter option: ")
                            if return_opt == "1":
                                returnItem(sale)
                            elif return_opt == "2":
                                returnAllitems(sale)
                                break
                            elif return_opt == "3":
                                break
                            else:
                                print("Invalid option. Please try again.")
                else:
                    print("Canceling order, returning items to inventory.")
                    returnAllitems(sale)
            else:
                print("No items added to sale.")
        elif option == "2":
            generateInventoryReport()
        elif option == "3":
            generateSalesReport()
        elif option == "4":
            break
        else:
            print("Invalid option. Please try again.")
    print("\nThank you for using the POS system. Have a great day!")

内容的提问来源于stack exchange,提问作者H-Y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:15:31