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

整数线性规划用户输入数据报错:TypeError类型不匹配问题求助

解决线性规划中的TypeError问题:int与str的+=运算不支持

嘿,这个问题我太熟啦!你遇到的TypeError: unsupported operand type(s) for +=: 'int' and 'str',根源其实很简单——Python的input()函数默认返回的是字符串类型,而你之后在做利润累加(比如+=操作)的时候,把字符串和整数混在一起运算了,这肯定会触发报错呀!

问题代码回顾

你原来的代码片段是这样的:

# 创建产品与服务列表
Products_Services = ['Herbal Products', 'Radix Jumbo', 'Radix IQ', 'Patients'] 
# 用户输入数据
HP_profits = input("Enter the profit from one bottle of Herbal Products: ") 
RJ_profits = input("Enter the profit from one unit of Radix Jumbo: ")
# 假设你之后会把这些值存入字典并做累加操作
profit_dict = {}
profit_dict['Herbal Products'] = HP_profits
# 这里尝试累加就会直接报错:
total_profit = 0
total_profit += profit_dict['Herbal Products']

解决方法:把输入转换成数值类型

只需要在获取用户输入的时候,用int()或者float()把字符串转成数值就行(利润可能有小数,更推荐用float()):

# 创建产品与服务列表
Products_Services = ['Herbal Products', 'Radix Jumbo', 'Radix IQ', 'Patients'] 
# 用户输入数据(转换为浮点数)
HP_profits = float(input("Enter the profit from one bottle of Herbal Products: ")) 
RJ_profits = float(input("Enter the profit from one unit of Radix Jumbo: "))
RIQ_profits = float(input("Enter the profit from one unit of Radix IQ: "))
# 存入字典
profit_dict = {
    'Herbal Products': HP_profits,
    'Radix Jumbo': RJ_profits,
    'Radix IQ': RIQ_profits
}
# 现在做累加操作就完全没问题了
total_profit = 0
total_profit += profit_dict['Herbal Products']
print(f"Total profit from Herbal Products: {total_profit}")

额外小提示

如果担心用户输入非数字内容导致报错,可以加个简单的输入验证,用try-except块兜底:

while True:
    try:
        HP_profits = float(input("Enter the profit from one bottle of Herbal Products: "))
        break
    except ValueError:
        print("请输入有效的数字哦!")

这样就能确保输入的是合法的数值,避免后续出现其他意外错误啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:55:16