gpt4 book ai didi

python - 为什么要避免 while 循环?

转载 作者:IT老高 更新时间:2023-10-28 22:16:48 25 4
gpt4 key购买 nike

我对 Python 作为一种入门语言的研究大约有 2 周的时间。我在 Zed 的 “Learn Python the Hard Way” 中提出了一个观点,他建议:

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

我已经在谷歌上搜索了所有内容,尽我所能引用了所有内容,但我在世界上找不到任何理由为什么这会成为 Python 中的约定。是什么让它与众不同?

当我 10 年前放弃编程时,我在 VB 中工作,并且经常被告知要摆脱我的 For 循环并改用 While 循环。我是个黑客(就像我今天一样,虽然我当时写了很多代码),所以我只是按照我被告知的去做,没有质疑它。好吧,现在我在质疑它。这是速度问题吗?只是为了避免无转义的无限吗?

最佳答案

这个建议对我来说似乎很糟糕。当您对某种集合进行迭代时,通常更好 使用 Python 的迭代工具之一,但这并不意味着 while 总是错误的。在很多情况下,您不会对任何类型的集合进行迭代。

例如:

def gcd(m, n):
"Return the greatest common divisor of m and n."
while n != 0:
m, n = n, m % n
return m

您可以将其更改为:

def gcd(m, n):
"Return the greatest common divisor of m and n."
while True:
if n == 0:
return m
m, n = n, m % n

但这真的是一种改进吗?我认为不会。

关于python - 为什么要避免 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4270167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com