Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

python - Why avoid while loops?

I'm about 2 weeks deep in my study of Python as an introductory language. I've hit a point in Zed's "Learn Python the Hard Way" where he suggests:

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

I've googled all over this, referenced everything I can, but I can't find any reason in the world why this would be a convention in Python. What makes it different?

When I gave up programming 10 years ago, I was working in VB and would regularly be told to get rid of my For loops and use While loops instead. I was a hack (as I am today, though I wrote a LOT of code back then), so I just did what I was told without questioning it. Well, now I'm questioning it. Is this a speed issue? Is it just to avoid escape-less infinites?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The advice seems poor to me. When you're iterating over some kind of collection, it is usually better to use one of Python's iteration tools, but that doesn't mean that while is always wrong. There are lots of cases where you're not iterating over any kind of collection.

For example:

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

You could change this to:

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

but is that really an improvement? I think not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...