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

Python中出现IndentationError: expected an indented block错误如何解决?

解决IndentationError及代码修复方案

错误核心原因

Python是强制缩进的语言,for items in NBAlist: 这行循环声明后,后续需要执行的代码(也就是你的print语句)必须缩进,否则会触发IndentationError。另外你的代码还存在未读取文件内容到NBAlist变量的问题,这也会导致后续运行报错。

修正后的代码

# 读取NBA数据文件并处理
NBAfile = open('NBA-Attendance-2015.txt', 'r')
# 读取文件所有行并处理成列表(假设每行数据用逗号分隔)
NBAlist = [line.strip().split(',') for line in NBAfile]

for items in NBAlist: 
    # Print out the team name, total attendance, average attendance, and capacity 
    # with appropriate formatting 
    print('The overall attendance at {0} was {1:,}, average attendance was {2:,} and the capacity was {3:.2f}%'.format(items[0], int(items[1]), int(items[2]), float(items[3])))

# Close the file 
NBAfile.close()

关键修改点

  • 缩进修复:将print语句缩进4个空格,使其成为for循环的代码块内容。
  • 添加文件读取逻辑:通过列表推导式读取文件每行内容,去掉换行符并按逗号分割字段,赋值给NBAlist变量(如果你的数据分隔符不是逗号,替换成对应符号即可)。
  • (可选优化)推荐使用with语句自动管理文件,避免手动关闭时的遗漏,代码如下:
# 使用with语句更安全
with open('NBA-Attendance-2015.txt', 'r') as NBAfile:
    NBAlist = [line.strip().split(',') for line in NBAfile]
    for items in NBAlist: 
        print('The overall attendance at {0} was {1:,}, average attendance was {2:,} and the capacity was {3:.2f}%'.format(items[0], int(items[1]), int(items[2]), float(items[3])))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:15:42