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

Python中如何在for循环调用range内特定值?代码报错求解

问题分析与解决

首先,你的代码存在两个关键问题:

  • 未定义rows变量:代码中使用了range(rows)但未给rows赋值,运行时会先触发NameError。
  • range(columns)[0]和range(columns)[-1]用法错误:range(columns)[0]会取出range序列的第一个整数元素(比如columns=3时结果是0),而for循环需要遍历可迭代对象(如列表、range本身),整数不属于可迭代对象,因此会报int object is not iterable错误。你的思路是给盒子加左右侧边,根本不需要用for循环,直接打印一次|即可。

修正后的基础版代码:

columns = int(input("How many columns? "))
rows = int(input("How many rows? "))  # 补充输入行数

for i in range(rows):
    # 打印左侧竖边
    print("|", end="")
    # 打印每行的横线部分
    for j in range(columns):
        print("_", end="")
    # 打印右侧竖边
    print("|")

如果想要更规整的带上下边框的网格,可调整为:

columns = int(input("How many columns? "))
rows = int(input("How many rows? "))

# 打印顶部边框
print("+" + "-"*columns + "+")
for i in range(rows):
    print("|" + "_"*columns + "|")
# 打印底部边框
print("+" + "-"*columns + "+")

补充说明:

  • 直接用print("|", end="")就能完成侧边竖线的打印,无需循环,因为你只需要输出一次。
  • 用"_"*columns可以直接生成对应长度的横线,比循环逐次打印更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:15:52