在Python中使用“for”的无限循环 [英] Infinite loops using 'for' in Python

查看:865
本文介绍了在Python中使用“for”的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不会造成无限循环?

  a = 5 
在范围内(1,a):
print(i)
a = a + 1

或这个

 我在范围内(1,4):
print(i)
i = i-1

或者这个

  4):
print(i)
i = 1

有没有办法我们可以使用循环创建无限循环?我知道有循环,但我只是好奇而已。

解决方案

范围是一个 class ,并且像例如 range(1,a)创建该类的对象。这个对象只能被创建一次,它不会在循环的每一次迭代中被重新创建。这是第一个例子不会导致无限循环的原因。



另外两个循环不是无限的,因为和范围不同对象,循环变量 i 是每次迭代重新创建(或者说是重新初始化的)。在循环内赋给 i 的值将被迭代循环覆盖。


Why does this not create an infinite loop?

a=5
for i in range(1,a):
  print(i)
  a=a+1

or this

for i in range(1,4):
  print(i)
  i=i-1

or this

for i in range(1,4):
  print(i)
  i=1

Is there any way we can create infinite loops using a for loop? I know there is the while loop for that but I was just curious.

解决方案

range is a class, and using in like e.g. range(1, a) creates an object of that class. This object is created only once, it is not recreated every iteration of the loop. That's the reason the first example will not result in an infinite loop.

The other two loops are not infinite because, unlike the range object, the loop variable i is recreated (or rather reinitialized) each iteration. The values you assign to i inside the loop will be overwritten as the loop iterates.

这篇关于在Python中使用“for”的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆