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

为何Python代码执行时出现TypeError: 'int' object is not iterable错误?

问题解决:TypeError: 'int' object is not iterable

直接报错原因

你代码里的两个for循环都犯了同一个错误:把整数直接当作迭代对象使用。Python的for...in循环要求后面必须是可迭代类型(比如列表、range对象),而整数t和10都是不可迭代的int类型,因此触发了这个错误。

完整修复后的代码

t = int(input())  # t is the number of Test cases
for _ in range(t):
    score = 0  # 每个测试用例单独初始化得分,避免跨用例累加
    for i in range(10):
        c = input()
        d = list(c)
        if d[0] == "X" or d[9] == "X":
            score += 1
        # 补全条件中漏写的 == "X" 判断
        if 0 < i < 9 and (d[1] == "X" or d[8] == "X"):
            score += 2
        if 1 < i < 8 and (d[2] == "X" or d[7] == "X"):
            score += 3
        if 2 < i < 7 and (d[3] == "X" or d[6] == "X"):
            score += 4
        if (i == 4 or i == 5) and (d[4] == "X" or d[5] == "X"):
            score += 5
    # 修复字符串拼接错误,用f-string实现格式化输出
    print(f"Score is {score} woho")

其他修复点说明

  • 将for i in t改为for _ in range(t):range(t)会生成0到t-1的可迭代序列,对应t个测试用例,用下划线_表示不需要使用该循环变量。
  • 将for i in 10改为for i in range(10):生成0到9的序列,匹配你后续判断i范围的逻辑。
  • 补全条件中的== "X":原代码里d[8]、d[7]、d[6]仅写了列表元素,未判断是否等于"X",会导致只要该位置非空就触发加分,不符合预期逻辑。
  • 把score = 0移到第一个循环内:确保每个测试用例的得分独立计算,不会和上一个测试用例的得分累加。
  • 修复print语句的字符串拼接错误:整数不能直接与字符串相加,用f-string格式化输出更简洁可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:20:16