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

Python运行出现ValueError: invalid literal for int() with base 10报错排查

错误原因
  • 输入转换逻辑无异常处理:check_input函数直接对用户输入执行int(user_input)转换,当用户输入非数字格式的字符串(如人名Mark)时,int()无法完成十进制整数转换,直接抛出你遇到的ValueError: invalid literal for int() with base 10错误。
  • 变量名不匹配:你定义的字典变量名为myDict,但主程序调用check_input时传入的参数是my_dict,变量名拼写不一致,修复转换问题后还会触发NameError。
修复方案

核心逻辑为给整数转换增加异常捕获逻辑,转换失败时跳过数值匹配步骤,同时修正变量名拼写问题:

修正后的输入校验函数

def check_input(user_input, dictionary): #input from user, and dictionary of people and number
    # 增加异常捕获,转换失败时numval设为None
    try:
        numval = int(user_input)
    except ValueError:
        numval = None
    for name, code in dictionary.items():
        # 仅当numval不为空时才做数值匹配
        if user_input == name or (numval is not None and numval == code):
            return True
    # 无匹配结果返回False,避免默认返回None
    return False

修正后的主程序代码

myDict = {'Mark':10, 'Harry':20, 'Richard':30}
chosenPerson = input('What Person do you want to pick?')
checkInput = check_input(chosenPerson, myDict)
if checkInput == True:
    # 此处替换为你的业务逻辑
    pass

修复后支持用户输入人名或者对应的数字编码两种校验方式,不会再触发转换报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:36:03