除了字母和数字外,如何正确循环尝试?

How do I properly loop try except with both letters and numbers?

我有一个完美运行的程序。 现在我为所有输入添加了错误检查。

如何在函数 add_one_item 中循环 new_name 输入和 new_qty 输入?

当前打印错误消息,但它们不会再次循环输入。如果您为 name 输入 3,则会打印错误消息,但它会移至 qty 字段。我该如何解决这个问题?

感谢您的宝贵时间。

代码:

import os

class Inventory:
    def __init__(self):
        self.item = []
        self.qty = []

    def remove(self, name):
        ix = self.item.index(name)
        self.item.pop(ix)
        self.qty.pop(ix)

    def add(self, name, qty):
        self.item.append(name)
        self.qty.append(qty)

    def update(self, name, update):
        if update >= 0:
            self.qty[self.item.index(name)] += update
        elif update <= -1:
            self.qty[self.item.index(name)] += update

    def search(self, name):
        pos = self.item.index(name) if name in self.item else -1
        if pos >= 0:
            return self.item[pos], self.qty[pos]
        else:
            return None

    def __str__(self):
        out = ""
        zipo = list(zip(self.item, self.qty))
        for foobar in zipo:
            out += f"Item : {foobar[0]} \nQuantity : {foobar[1]}\n"
            out += "----------\n"
        return out


def menuDisplay():
    """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):
    print('Adding Inventory')
    print('================')
    while True:
        try:
            new_name = input('Enter the name of the item: ')
            if not new_name.isalpha():
                print("Only letters are allowed!")
                print()
            new_qty = int(input("Enter the quantity of the item: "))
            inventory.add(new_name, new_qty)
            break
        except Exception as e:
                print("Invalid choice! try again! " + str(e))
                print()
        continue


def remove_one_item(inventory):
    print('Removing Inventory')
    print('==================')
    removing = input('Enter the item name to remove from inventory: ')
    inventory.remove(removing)


def ask_exit_or_continue():
    return int(input('Enter 98 to continue or 99 to exit: '))


def update_inventory(inventory):
    print('Updating Inventory')
    print('==================')
    item = input('Enter the item to update: ')
    update = int(input(
        "Enter the updated quantity. Enter 5 for additional or -5 for less: "))
    inventory.update(item, update)


def search_inventory(inventory):
    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:
        name, qty = result
        print('Item:     ', name)
        print('Quantity: ', qty)
        print('----------')


def print_inventory(inventory):
    print('Current Inventory')
    print('=================')
    print(inventory)


def main():
    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()

由于您已经设置了一个循环,如果出现异常将继续,一个简单的解决方案是在名称包含 non-letters:

时引发异常
def add_one_item(inventory):
    print('Adding Inventory')
    print('================')
    while True:
        try:
            new_name = input('Enter the name of the item: ')
            assert new_name.isalpha(), "Only letters are allowed!"
            new_qty = int(input("Enter the quantity of the item: "))
            inventory.add(new_name, new_qty)
            break
        except Exception as e:
            print(f"Invalid choice! try again! {e}\n")

这就是 try/except 在许多情况下比使用 if/else 检查错误条件更好的原因——你可以非常干净地让一个 except 处理一堆异常不同的地方,你可以决定什么是例外,什么不是例外!在这种情况下,如果输入不符合您的要求,assert 将引发异常,就像如果输入不是有效的整数字符串,int() 函数将引发异常一样。

请注意,您不需要在循环体末尾使用 continue;它会自动继续,除非你 breakreturn.

您需要分离 while 循环才能使其最干净地工作:

while True:

    x = input("...")
    if x.isalpha():
        break
    print("error message")

while True:
    try:
        y = int(input("..."))
        break
    except ValueError as e:
        print("error message")