Python 计算迭代次数
我知道代码执行了8次。但是,是检查了8次还是9次Python 计算迭代次数,python,python-3.x,loops,Python,Python 3.x,Loops,我知道代码执行了8次。但是,是检查了8次还是9次 for num in range(2, 10): if num % 2 == 0: print("Found an even number", num) continue print("Found a number", num) for:检查或评估的次数为定义for条件的+1倍 如果:根据定义的条件检查或评估的次数 检查如下: 分配→[核对→跑体→增量]∗→
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
for:检查或评估的次数为定义for条件的+1倍 如果:根据定义的条件检查或评估的次数 检查如下: 分配→[核对→跑体→增量]∗→检查→出口
程序将循环8次。由于执行了
if
和continue
不同的print
语句
In [51]: loop_count = 0
In [52]: for num in range(2, 10):
...: loop_count+=1
...: print(loop_count)
...: if num % 2 == 0:
...: print("Found an even number", num)
...: continue
...: print("Found a number", num)
...:
1
Found an even number 2
2
Found a number 3
3
Found an even number 4
4
Found a number 5
5
Found an even number 6
6
Found a number 7
7
Found an even number 8
8
Found a number 9
范围对象被检查9次。前8次返回数字2到9(总共8个数字)。在第9次检查时,范围对象命中10,命中其结束条件,并引发
StopIteration
。for的接受该异常并退出循环
如果我们用自己的计数器在循环中迭代range对象,我们就会看到它在起作用
>>> count = 1
>>> range_iter = iter(range(2,10))
>>> while True:
... print(count)
... count += 1
... x = next(range_iter)
...
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
StopIteration
>>>
>>计数=1
>>>范围=国际热核实验堆(范围(2,10))
>>>尽管如此:
... 打印(计数)
... 计数+=1
... x=下一个(范围)
...
1.
2.
3.
4.
5.
6.
7.
8.
9
回溯(最近一次呼叫最后一次):
文件“”,第4行,在
停止迭代
>>>
迭代次数将为8次,因为您从2开始迭代,正如您在范围(2,10)中提到的那样。因为范围(起点、终点)8次(10-2次),您可以在每次迭代中打印“找到一个数字”
或“找到一个偶数”
。每次迭代都会得到一条消息,而if
条件决定打印哪条消息。由于您收到八条消息,因此执行了八次if
条件。如果是第九次评估,你会得到第九条消息。你指的是哪一个“it”?