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

Python try-except输入校验:出错后重试当前项而非返回首个输入

问题原因

你把所有输入逻辑都放在同一个外层while True循环和同一个try块中,只要任意字段触发校验失败、执行continue,就会直接回到外层循环的起始位置,导致所有已填内容作废,需要从头开始输入。

修复方案

给每个输入字段单独配置校验循环:当前字段输入符合规则、校验通过后,再进入下一个字段的输入流程;如果当前字段输入错误,只会在当前字段的小循环内重复提示重输,不会影响之前已经校验通过的内容。

直接修改后的代码

# 校验客户名
while True:
    customer_name = input("Enter updated customer name: ")
    if not customer_name.isalpha():
        print("Customer names should not contain numbers!")
        continue
    break

# 校验套餐名
while True:
    package_name = input("Enter updated package name: ")
    if not package_name.isalpha():
        print("Package names should not contain numbers!")
        continue
    break

# 校验人数
while True:
    try:
        number_pax = int(input("Enter updated pax: "))
        break
    except ValueError:
        print("Invalid input, only numbers allowed!")

# 校验单人成本
while True:
    try:
        pax_cost = int(input("Enter updated cost per pax: $"))
        break
    except ValueError:
        print("Invalid input, only numbers allowed!")

# 此处可追加后续业务逻辑,四个变量均为合法值

注:原代码中package_name = str(input(...))的str()转换是多余操作,input()本身返回值就是字符串类型,无需额外转换。

可选优化:封装通用校验函数减少重复代码

如果后续有更多同类输入校验需求,可以把重复的循环校验逻辑封装成通用函数,简化代码:

def get_alpha_input(prompt, error_msg):
    while True:
        res = input(prompt)
        if res.isalpha():
            return res
        print(error_msg)

def get_int_input(prompt, error_msg):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print(error_msg)

# 直接调用函数获取合法输入
customer_name = get_alpha_input("Enter updated customer name: ", "Customer names should not contain numbers!")
package_name = get_alpha_input("Enter updated package name: ", "Package names should not contain numbers!")
number_pax = get_int_input("Enter updated pax: ", "Invalid input, only numbers allowed!")
pax_cost = get_int_input("Enter updated cost per pax: $", "Invalid input, only numbers allowed!")
实现效果
  • 客户名、套餐名输入包含非字母内容时,仅重复提示当前名称项重新输入,已通过校验的内容不会被清空
  • 人数、单人成本输入非整数内容触发类型转换异常时,仅停留在当前数字输入项要求重输,不需要回溯重填之前的字段
  • 所有字段依次校验通过后,才会执行后续业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:01:06