简体   繁体   English

如何修复此 function 以适用于我程序中的所有选项?

[英]How do I fix this function to work for all options in my program?

I have an inventory program that worked 100% until I needed to change option 4 (Search Item in Inventory) to be able to search by characters in an items name than by ID number.我有一个 100% 工作的库存程序,直到我需要更改选项 4(在库存中搜索项目)以便能够按项目名称中的字符而不是 ID 号进行搜索。

This function is def search(self, query) : .这个 function 是def search(self, query) : 。 The function works when you are searching for data previously saved, but it now does not allow you to add anything to inventory (option 1) when trying to add items to inventory I get this error: function 在您搜索以前保存的数据时有效,但它现在不允许您在尝试将项目添加到库存时向库存添加任何内容(选项 1)我收到此错误:

in <string>' requires string as left operand, not int. 

Here is the full code as you need everything to see all of the different functions that are affected.这是完整的代码,因为您需要一切才能查看受影响的所有不同功能。

import os
import json

class Inventory:
    def __init__(self):
        #AT LAUNCH GROUPS AND LOADING FUNCTION
        self.items = {}
        self.load()

    def remove(self, ID):
        #REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
        del self.items[str(ID)]
        self.save()

    def add(self, ID, name, qty):
        #ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
        self.items[str(ID)] = {"name": name, "qty": qty}
        self.save()

    def update(self, ID, update):
        #UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
        self.items[str(ID)]["qty"] += update
        self.save()

    def search(self, query):
        for id in self.items:
            if query in self.items[id]['name']:
                return id, self.items[id]['name'], self.items[id]['qty']
        return None

    def __str__(self):
        #FORMATTING
        out = ""
        for id, d in self.items.items():
            out += f"ID Number : {id} \nItem Name : {d['name']}\nQuantity : {d['qty']}\n"
            out += "----------\n"
        return out
    
    def save(self):
        #WHERE TO SAVE TO
        with open('data.txt','w') as outfile:
           json.dump(self.items, outfile)

    def load(self):
        #WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
        try:
            with open('data.txt','r') as json_file:
               self.items = json.load(json_file)
        except:
            print("Can't load old inventory, starting fresh")
            self.items = {}


def menuDisplay():
    #MENU FOR PROGRAM 
    """Display the menu"""
    print('=============================')
    print('= Inventory Management Menu =')
    print('=============================')
    print('(1) Add New Item to Inventory')
    print('(2) Remove Item from Inventory')
    print('(3) Update Inventory')
    print('(4) Search Item in Inventory')
    print('(5) Print Inventory Report')
    print('(99) Quit')


def add_one_item(inventory):
    #ADDING PROMPT AND ERROR CHECKING
    print('Adding Inventory')
    print('================')
    while True:
        try:
            new_ID = int(input("Enter an ID number for the item: "))
            if inventory.search(new_ID):
                print("ID number is taken, please enter a different ID number")
                continue
            new_name = input('Enter the name of the item: ')
            new_qty = int(input("Enter the quantity of the item: "))
            inventory.add(new_ID, new_name, new_qty)
            break
        except Exception as e:
            print("Invalid choice! try again! " + str(e))
            print()


def remove_one_item(inventory):
    #REMOVING PROMPT AND ERROR CHECKING
    print('Removing Inventory')
    print('==================')
    removing = int(input("Enter the item's ID number to remove from inventory: "))
    inventory.remove(removing)


def ask_exit_or_continue():
    #OPTION TO CONTINUE OR QUITE PROGRAM
    return int(input('Enter 98 to continue or 99 to exit: '))


def update_inventory(inventory):
    #UPDATING PROMPT AND ERROR CHECKING
    print('Updating Inventory')
    print('==================')
    while True:
        try:
            ID = int(input("Enter the item's ID number to update: "))
            if inventory.search(ID):
                update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
                inventory.update(ID, update)
            else:
                print("ID number is not in the system, please enter a different ID number")
                continue
            break
        except Exception as e:
            print("Invalid choice! try again! " + str(e))
            print()

def search_inventory(inventory):
    #SEARCHING PROMPT AND ERROR CHECKING
    print('Searching Inventory')
    print('===================')
    search = input("Enter the name of the item: ")
    result = inventory.search(search)
    if result is None:
        print("Item not in inventory")
    else:
        ID, name, qty = result
        print('ID Number: ', ID)
        print('Item:     ', name)
        print('Quantity: ', qty)
        print('----------')


def print_inventory(inventory):
    #PRINT CURRENT LIST OF ITEMS IN INVENTORY
    print('Current Inventory')
    print('=================')
    print(inventory)


def main():
    #PROGRAM RUNNING COMMAND AND ERROR CHECKING
    inventory = Inventory()
    while True:
        try:
            menuDisplay()
            CHOICE = int(input("Enter choice: "))
            if CHOICE in [1, 2, 3, 4, 5]:
                if CHOICE == 1:
                    add_one_item(inventory)
                elif CHOICE == 2:
                    remove_one_item(inventory)
                elif CHOICE == 3:
                    update_inventory(inventory)
                elif CHOICE == 4:
                    search_inventory(inventory)
                elif CHOICE == 5:
                    print_inventory(inventory)
                exit_choice = ask_exit_or_continue()
                if exit_choice == 99:
                    exit()
            elif CHOICE == 99:
                exit()
        except Exception as e:
            print("Invalid choice! try again!"+str(e))
            print()

        # If the user pick an invalid choice,
        # the program will come to here and
        # then loop back.


main()

I believe the problems lie in def add , def add_one_item(inventory) , and def search .我认为问题在于def adddef add_one_item(inventory)def search

The problem is in this function:问题出在这个function:

    def search(self, query):
        for id in self.items:
            if query in self.items[id]['name']:
                return id, self.items[id]['name'], self.items[id]['qty']
        return None

query is an int , while self.items[id]['name'] is a string, so you cannot do if query in self.items[id]['name'] . query是一个int ,而self.items[id]['name']是一个字符串,所以你不能if query in self.items[id]['name'] That is what the error is trying to tell you.这就是错误试图告诉您的内容。

Simply add a str wrapping around query :只需添加一个str环绕query

    def search(self, query):
        for id in self.items:
            if str(query) == id:
                return id, self.items[id]['name'], self.items[id]['qty']
        return None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM