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

Python CLI库存数据库脚本返回主菜单重复显示问题如何解决?

问题原因
  • 核心逻辑错误:你在「返回主菜单」的分支中主动调用了一次mainmenu(),这次调用获取的用户输入不会被任何判断逻辑处理。内层循环结束后,外层的while True会自动再次调用mainmenu(),等于连续触发两次主菜单输入要求,只有第二次的输入才会被外层逻辑响应,所以出现第一次输入无响应、菜单重复弹出的问题。
  • 额外bug:SQL插入逻辑重复执行了两次,同一个物品会被写入两次库存,且if(cursor.execute(query,data))的判断逻辑无效,cursor.execute的返回值不能用来判断插入是否成功。
修复方案

直接删除「返回主菜单」分支下的mainmenu()调用即可,同时修正重复插入的问题,修正后代码如下:

# Main Menu Options
import sqlite3
# 此处替换为你原本的数据库连接逻辑
con = sqlite3.connect("inventory.db")
cursor = con.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS items(devicetype TEXT, quantity INT)")

def mainmenu():
    print("(1) Add (Brand) New Item to Inventory")
    print("(2) Remove Item from Inventory")
    print("(3) Update Inventory")
    print("(4) Print Current Inventory Report")
    print("(5) '99' to quit")
    print("_" * 32)
    global choice_1
    choice_1 = int(input("Enter Choice:"))

while True:
    mainmenu()
    # 退出逻辑
    if choice_1 == 99:
        con.close()
        break
    # (1) 添加物品逻辑
    if choice_1 == 1:
        while True:
            print("What item would you like to add? (eg. 'keyboards', 'laptops', etc.)")
            add_item = input("Enter Choice:").casefold()
            print(f"Enter quantity of {add_item}:")
            quantity = int(input())

            # 修正重复执行SQL的问题
            query = "INSERT into items(devicetype,quantity)VALUES (?,?)"
            data = (add_item, quantity)
            try:
                cursor.execute(query,data)
                con.commit()
                print(f"Added {quantity} {add_item} to Inventory successfully.")
            except Exception as e:
                print(f"Could not add {add_item} to Inventory. Error: {e}")
            
            print()
            print("Would you like to add another new item to invenotry or return to main menu?")
            print()
            print("(1) Return to main menu:")
            print("(2) Add another item to inventory:")
            print()
            main_menu_choice_1 = int(input("Enter choice here:"))

            if main_menu_choice_1 == 1:
                # 直接break内层循环即可,外层会自动调用主菜单
                break
            elif main_menu_choice_1 == 2:
                continue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:45:03