我如何让这个 for 循环打印

How do I get this for loop to print

有没有人知道为什么我的 for 循环中总是出现以下错误?任何见解将不胜感激和有帮助。

the_count = [1, 2, 3, 4, 5]
for number in the_count:
print(f"This is count {number}")

NameError                                 Traceback (most recent call last)
<ipython-input-3-e3d6b461f13e> in <module>
----> 1 print(f"This is count {number}")

NameError: name 'number' is not defined

嗯,它应该给出缩进错误,但它给出了名称错误

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")

这就是您的代码应有的样子。

您是运行在终端中逐行还是将其作为 .py 文件?如果您 运行 将此代码作为 python 文件,则此代码可以完美运行。

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")

输出:

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5

如果您逐行 运行 这段代码,您可能 运行 在 for 循环中出错,因为 for 循环甚至在读取打印语句之前就已完全执行。

这里有几种打印循环的方法:

# Option 1
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print('This is count:' + str(x))

# Option 2
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print(f"This is count {x}")