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

报错ValueError: invalid literal for int() with base 10: 'C',求定位字符串转整数位置

问题定位与修复:字符串转整数报错ValueError

运行代码时触发错误:ValueError: invalid literal for int() with base 10: 'C',以下是问题分析与修复方案:

原代码

def baseball_game (ops):
  record = []
  for i in range (len(ops)):
    if ops[i] == 'C': 
      record.pop()   #I remove last element. I am mot converting into integer.
      print(record)
    if ops[i] == 'D':
      record.append(record[-1] * 2)  #I am doubling the value of last element, which is already an integer.
      print(record)
    if ops[i] == '+':
      record.append(record[-1] + record[-2]) #I am adding last 2 elements, which are NOT integers.
      print(record)
    else:
      record.append(int(ops[i])) #I am converting into integer any value which is NOT 'C', 'D' nor '+'
      print(record)
  return sum(record)

问题定位

你当前使用了三个独立的if语句而非elif。当ops[i]为'C'时,第一个if分支执行record.pop()后,后续两个if分支条件不成立,程序会进入else分支,执行int('C')的转换操作——这就是报错的根源。

简单说:'C'虽然被第一个if处理了,但还是会走到else里去转整数,导致报错。

修复方案

把后续的if替换为elif,确保每个循环周期只有一个分支执行,同时可以优化循环方式,直接遍历元素而非通过索引访问:

def baseball_game(ops):
    record = []
    for op in ops:
        if op == 'C':
            record.pop()
            print(record)
        elif op == 'D':
            record.append(record[-1] * 2)
            print(record)
        elif op == '+':
            record.append(record[-1] + record[-2])
            print(record)
        else:
            record.append(int(op))
            print(record)
    return sum(record)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:10:22