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

如何实现输入类型校验,错误时返回对应输入的Pythonic优化方案?

优化Python输入校验逻辑

原代码通过全局循环控制所有输入的校验,一旦某个输入类型错误,所有输入都要重新开始,且写法冗余。下面是优化后的实现,满足单个输入错误仅重输当前项的需求,同时更符合Python风格:

优化后的代码

def get_input(prompt, input_type):
    while True:
        try:
            return input_type(input(prompt))
        except ValueError:
            print(f"请输入有效的{input_type.__name__}类型数据!")

def set_values():
    juvenile_population = get_input("Enter the population of the juvenile greenfly (1000s) > ", int)
    juvenile_survival_rate = get_input("Enter the survival rate of juvenile greenfly (decimal) > ", float)
    adult_population = get_input("Enter the population of the adult greenfly (1000s) > ", int)
    adult_survival_rate = get_input("Enter the survival rate of adult greenfly (decimal) > ", float)
    senile_population = get_input("Enter the population of the senile greenfly (1000s) > ", int)
    senile_survival_rate = get_input("Enter the survival rate of senile greenfly (decimal) > ", float)
    birth_rate = get_input("Enter the birthrate of the greenfly > ", float)
    
    # 可添加后续逻辑,比如返回收集到的参数
    return (juvenile_population, juvenile_survival_rate,
            adult_population, adult_survival_rate,
            senile_population, senile_survival_rate, birth_rate)

优化说明

  • 提取通用输入函数:把输入提示、类型转换、错误捕获逻辑封装到get_input函数中,避免重复代码,符合DRY(Don't Repeat Yourself)原则。
  • 异常捕获替代类型判断:原代码用isinstance事后判断类型,而Python中处理输入类型校验的标准做法是用try-except捕获ValueError,更高效准确。
  • 单个输入独立校验:每个输入单独调用get_input,仅当前输入错误时循环重试,不影响已输入正确的内容。
  • 变量名符合PEP8规范:将原大驼峰变量名改为小写加下划线形式,契合Python官方命名规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:27:52