Why avoid while loops?

后端 未结 13 1167
失恋的感觉
失恋的感觉 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:15

    The general issue with while loops is that it is easy to overlook, or somehow skip the statement where the loop variable gets incremented. Even a C for-loop can have this problem - you can write for(int x=0; x<10;), although it is unlikely. But a Python for loop has no such problem, since it takes care of advancing the iterator for you. On the other hand, a while loop forces you to implement a never fail increment.

    s = "ABCDEF"
    i = 0
    while (i < len(s)):
        if s[i] in "AEIOU":
            print s[i], 'is a vowel'
            i += 1
    

    is an infinite loop as soon as you hit the first non-vowel.

提交回复
热议问题