首页 > 解决方案 > 使用 for 循环定义的变量来打印数字(错误)(python)

问题描述

我正在尝试检查一个数字是否为素数。为此,我使用带有“范围”功能的“for循环”。事实证明,不能使用迭代范围的变量来使用 Python 的 'format()' 属性进行打印。

我的代码的基本问题在下面的简化代码中给出。

for num in range[1,4,1]:
    print("{} is a number").format(num)

我希望输出是

1 is a number 
2 is a number
3 is a number

但输出是

$python main.py
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    for num in range[1,4,1]:
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

标签: python-3.x

解决方案


Range 不能这样工作,您需要使用括号而不是方括号:

for num in range(1,4,1) :
    print("{} is a number".format(num))

推荐阅读