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

如何修复Python学生身高求和代码中的ValueError: invalid literal for int() with base 10:错误?

解决:ValueError: invalid literal for int() with base 10

报错原因

你输入的学生身高列表里如果包含无法转换为整数的内容(比如多余空格、字母、小数点、特殊符号),int()函数没法把这类字符串转成整数,就会触发这个错误——它只能处理纯数字的字符串。

修复方案

方案1:添加异常处理,自动跳过无效数据

修改后的代码会捕获转换失败的情况,跳过无效内容并给出提示:

student_heights = input("输入学生身高列表(用空格分隔) ").split()

total_height = 0
for height_str in student_heights:
    # 先去除字符串两端空白,避免多余空格导致的问题
    height_str = height_str.strip()
    try:
        height = int(height_str)
        total_height += height
    except ValueError:
        print(f"警告:'{height_str}' 不是有效的整数身高,已跳过该数据")

print(f"有效身高总和:{total_height}")

方案2:提前过滤非数字内容

如果想直接筛掉无效输入项,可以用isdigit()方法(注意:该方法不识别负号,适合不会输入负身高的场景):

student_heights = input("输入学生身高列表 ").split()

valid_heights = []
for height_str in student_heights:
    height_str = height_str.strip()
    if height_str.isdigit():
        valid_heights.append(int(height_str))
    else:
        print(f"跳过无效数据:{height_str}")

total_height = sum(valid_heights)
print(f"有效身高总和:{total_height}")

方案3:支持小数身高输入

如果身高数据包含小数(比如172.5),可以将int()替换为float(),之后按需处理整数或小数输出:

student_heights = input("输入学生身高列表 ").split()

total_height = 0.0
for height_str in student_heights:
    height_str = height_str.strip()
    try:
        height = float(height_str)
        total_height += height
    except ValueError:
        print(f"警告:'{height_str}' 不是有效的身高数据,已跳过")

# 转换为整数输出
print(f"身高总和(取整):{int(total_height)}")
# 保留两位小数输出
print(f"身高总和(精确到两位小数):{total_height:.2f}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:15:51