python - 素数程序中的范围函数
问题描述
这是一个打印从 2 到 11 的素数的程序。
for num in range(2,12):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print num
在最后一次迭代期间的第二个 for 循环中,num=11 的值 .. 所以范围应该取 num 为 10 即 (n-1) 但在这个程序中,值 11 仍然被打印出来 .. 那是怎么回事?
解决方案
num
is indeed 11, and it is num
that is being printed:
if prime:
print num
The range(2, num)
range goes from 2 through to 10, inclusive, but the for
loop over that range uses i
as the target, not num
:
for i in range(2, num):
# ^ the target of the for loop
So it is the value of i
, not num
that goes from 2 through to 10, and i
is never printed. The value of num
is not changed by the inner loop, it remains set to 11 all the way through. So yes, it'd be surprising if 10
was printed instead.
Note that the print num
line is only ever executed if prime
is still set to True
. It would be set to False
if num
was divisible by any of the i
values. For 11
, there is no value between 2 and 10 (inclusive) that can divide 11, so prime
remains set to True
and num
is printed.
推荐阅读
- excel - 尝试选择 OLAP 数据透视字段数组元素时出现运行时错误 1004
- google-bigquery - 我是否需要指定整个架构才能将数据附加到现有的 Google BigQuery 表中?
- gtk2 - 如何修复 GTK+2 中的“assertion 'GDK_IS_SCREEN (screen)' failed”错误
- django - Django 基于类的视图,一旦用户登陆页面,就将 request.session 设置为某个值
- java - 如何在List中使用excel数据
- c# - 在使用 EF Core 的通用存储库中包含使用反射的所有二级导航属性
- c# - 如何判断对象是放大还是缩小?
- html - 为什么我的弹性项目垂直溢出其父项?我怎样才能让弹性项目高度随父项缩小和增长?
- c - C中一维数组的元素在特定索引后不显示
- java - 如何将 JSON 从静态文件传递到休息控制器 SpringBoot App