python - while 循环和 python

标签 python performance while-loop infinite-loop

<分区>

Possible Duplicate:
Why avoid while loops?

我正在尝试通过关注 Learn Python The Hard Way 来学习 Python随着我的进步,我发现网站上提到,

Use a while-loop only to loop forever, and that means probably never. This only applies to Python, other languages are different.

现在我基本上是一名 Java 开发人员,这让我想知道为什么 while 应该避免在 python 中使用,尽管它在 Java 中被广泛使用。我无法在互联网上找到任何答案。

最佳答案

该声明非常主观,我不确定我是否同意。在 Python 中使用 while 很容易产生无限循环:

  while True:
       # do stuff

也许作者是将其与 C 进行比较,C 也很容易使用 for 进行无限循环:

  for(;;)
      /* do stuff */

Python 不存在这样的对应结构。

话虽如此,无限循环在很多情况下都是有用的(在任何语言中)——想想事件循环,或者可以通过无限循环简化循环控制,并且只有某些情况会导致 break

您经常会处理列表和字符串等序列,使用 for 循环将是一种自然的选择,但我不会仅仅因为这个原因而忽略 while 循环。

关于python - while 循环和 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11309346/

相关文章:

python 3 : Removing an empty tuple from a list of tuples

python - 本地 HTML 文件抓取 Urllib 和 BeautifulSoup

python - 在 Python 中解析 1 亿条 A 记录的最快方法

性能计数器与 ETW

r 不允许在我的 while() 循环中进行 100 次迭代

python - 使用 PYTHON 计算在 while 循环中设置新变量

python - 嵌套 json 到 Pandas 非常慢

python - 在 python 中将年/季度日期格式更改为上一个时期

performance - 无法找到为什么一些小图片需要 10 秒才能加载

c - while 循环在输入错误后一直忽略 scanf