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

如何避免非数字输入导致Python对话程序崩溃?

问题分析

你的代码崩溃的核心原因:

  • 在your_age的循环逻辑里,你先执行了your_age = int(input('How old are you?')),这一步如果用户输入非数字(比如'one'),会直接抛出ValueError,而这个异常不在try块的覆盖范围内,因此无法被捕获,直接导致程序崩溃。
  • my_age的输入完全没有验证逻辑,输入非数字时同样会直接崩溃。
解决方案

我们需要把输入读取和类型转换操作放在try块内部,确保所有可能抛出异常的步骤都能被捕获。同时可以封装一个通用函数,避免重复编写验证逻辑,让your_age和my_age的输入都能复用这个逻辑。

修改后的代码如下:

name = input('Salutations what is your name?') # 用户输入姓名并保存
print('That is a nice name ' + name + ', whats your favorite color?') # 生成问候语句

color = input('') # 收集用户喜欢的颜色
print(f'{color} is a great color!') # 反馈用户的选择

# 封装通用函数:获取整数输入,直到用户输入有效数字
def get_int_input(prompt):
    while True:
        user_input = input(prompt)
        try:
            return int(user_input)
        except ValueError:
            print('INVALID: 请输入数字形式的年龄,可以四舍五入后输入')

# 获取有效年龄输入
your_age = get_int_input('How old are you?')
my_age = get_int_input('How old am I?')

# 计算并输出合并年龄
combined_age = your_age + my_age
print(f'Our combined age is {combined_age}')
关键改动说明
  • 新增get_int_input函数:统一处理所有需要整数输入的场景,循环获取用户输入,直到输入能成功转换为整数为止。
  • 输入读取与类型转换移至try块内:确保输入非数字时,异常能被except捕获,然后提示错误并重新发起输入请求。
  • 使用f-string格式化字符串:让代码更简洁易读(也可以保留原有的字符串拼接方式,这是优化建议)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:47:25