python-3.x - 使用 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__'
解决方案
Range 不能这样工作,您需要使用括号而不是方括号:
for num in range(1,4,1) :
print("{} is a number".format(num))
推荐阅读
- xcode - 从命令行运行应用程序时是否可以启用 GuardMalloc 和 Zombie Objects?
- javascript - 异步/等待问题(返回未定义)猫鼬
- c# - 解决方案中的依赖/引用设置问题(未找到程序集/未找到文件)
- javascript - Amazon S3 存储桶策略公开
- java - 测试 lambda 工厂是否返回正确的结果
- react-native - 抽屉内的 React Native 嵌套堆栈导航器导致导航上的无限 useEffect 循环
- html - 复选框按钮引导程序上的自定义颜色
- excel - 根据值删除特定列中的行
- android - 反应本机小米手机 axios 不工作
- mysql - 使用 SQL 获取已购买商品的数量 - Woocommerce