C语言 for循环的无限循环在python可以做到吗?



我们可以执行多少次print语句?

for i in range (1,6,-1):
print(done)

答案是none。但是在C语言中,如果我们写这段代码,它在无限模式下运行。为什么?

int i;
for (i=5; i<=10; i--)
{
printf("what happens");
}

我在python中尝试过,它甚至没有运行,但在C中它运行了无限次,为什么?

对于循环,PythonC有一个根本的区别:

  • Python:循环在(有限)序列的元素上执行,并且只要该序列中还有剩余元素就继续执行。复合语句- for语句)

  • C:只要满足条件就继续循环([CPPReference]: for loop)。为了复制序列迭代行为,一些语言有foreach

如前所述:

  1. 代码片段中的C示例不是无限的,而是依赖于绕行数学(当超出整型界限时),并且(对于大多数实现)将执行232- 5
    如果你想在C中使用一个真正的无限循环,使用:for (;;)

  2. 你可以使用while循环代替

由于Python的for循环的性质,您想要的行为不能被复制OOTB。但是有一些技巧(将while转换为的)。
这可以通过[Python]来完成。文档:itertools.cycle (iterable):

>>> import itertools as its
>>>
>>>
>>> it = its.cycle([None])  # Infinite iterable
>>>
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
>>>
>>> for _ in it:
...     if input("Press 'n' to exit: ").lower() == "n":
...         break
...
Press 'n' to exit: y
Press 'n' to exit: 
Press 'n' to exit: A
Press 'n' to exit: Y
Press 'n' to exit: t
Press 'n' to exit: 1.618
Press 'n' to exit: sdf54
Press 'n' to exit: n
>>>

Python中第二个代码段的等价表达式为

i = 5
while i <= 10:
print('what happens')
i -= 1

由于i每循环减少1,并且永远不会超过10,因此循环永远不会退出。

x = [1] 
for i in x:
#your_works 
x+=[1]

最新更新