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

如何利用异常简化重复的用户输入循环验证逻辑?

简化输入验证逻辑的方案

你这段代码的核心问题是重复写了四次几乎一样的输入校验循环,我们可以把这部分逻辑抽成通用函数,既保留循环+异常处理的校验能力,又能大幅减少冗余代码。

重构后的完整代码

import csv

def get_valid_input(prompt, convert_func, error_msg, extra_check=None):
    while True:
        user_input = input(prompt)
        try:
            converted_value = convert_func(user_input)
        except ValueError:
            print(error_msg)
            continue
        # 执行额外校验(比如非空、数值范围检查)
        if extra_check is not None and not extra_check(converted_value):
            continue
        return converted_value

class InventoryManager:
    def __init__(self):
        self.result = []

    def add_item(self):
        # 调用通用函数获取各字段输入
        item_num = get_valid_input(
            "What is the items #?\n",
            int,
            "That's not an int!"
        )
        price = get_valid_input(
            "What is the items price?\n",
            float,
            "That's not a float!"
        )
        quant = get_valid_input(
            "What is the items quantity?\n",
            int,
            "That's not an int!"
        )
        name = get_valid_input(
            "What is the items name?\n",
            str,
            "That's not a string!",
            # 额外校验:名字不能为空
            lambda x: x != "" or (print("Ha! You have to enter a name!"), False)[1]
        )

        new_row = [item_num, price, quant, name]
        with open("Items2.csv", "a+") as fp:
            reader = csv.reader(fp)
            fp.seek(0)
            labels = next(reader, None)
            writer = csv.writer(fp)
            if labels:  # 确保有表头才创建字典
                new_record = dict(zip(labels, new_row))
                self.result.append(new_record)
                writer.writerow(new_record.values())
            print("Item Added! Check Inventory Again to see!")

关键优化点说明

  • 通用输入函数get_valid_input:把循环、异常捕获、结果返回的逻辑封装起来,通过参数传递不同的提示文本、类型转换函数(int/float/str)、错误提示,甚至可以传入额外的校验规则(比如名字非空)。
  • 简化add_item逻辑:原来的四个校验循环变成四行函数调用,代码结构更清晰,可读性更强,后续要加新字段也只需要新增一行调用即可。
  • 兼容空表头场景:新增了if labels:的判断,避免文件刚创建还没有表头时出现zip空值的问题(可选优化,不影响原有功能)。

扩展说明

如果需要更复杂的校验规则,比如价格必须大于0、数量不能为负,只需要给get_valid_input传对应的extra_check函数就行,比如:

price = get_valid_input(
    "What is the items price?\n",
    float,
    "That's not a float!",
    lambda x: x > 0 or (print("Price can't be zero or negative!"), False)[1]
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:10:43