Why avoid while loops?

后端 未结 13 1154
失恋的感觉
失恋的感觉 2020-12-09 15:24

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:

13条回答
  •  轮回少年
    2020-12-09 16:21

    Let me share a secret with you: Nine times out of ten with python, the answer is just "use common sense". It's not a terribly tricky language (aside from some notable gotchas). In this case, I'd consider Zed's rule of thumb superfluous because it's almost always common sense to know what kind of loop to use.

    That said, if I run into a situation that requires iteration and I have a choice, I prefer the following (from greatest to least preference):

    1. List/generator/set/dict comprehension
    2. For loop
    3. While loop
    4. Recursion

    Comprehensions are simple, but it's surprising how many times you can make a for loop into one if you put thought into it. But generally, I'd say that about 90% of all iteration I'll do is with a list comprehension or a for loop.

提交回复
热议问题