Why avoid while loops?

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

    It's because in the typical situation where you want to iterate, python can handle it for you. For example:

    >>> mylist = [1,2,3,4,5,6,7]
    >>> for item in mylist:
    ...     print item
    ... 
    1
    2
    3
    4
    5
    6
    7
    

    Similar example with a dictionary:

    >>> mydict = {1:'a', 2:'b', 3:'c', 4:'d'}
    >>> for key in mydict:
    ...     print "%d->%s" % (key, mydict[key])
    ... 
    1->a
    2->b
    3->c
    4->d
    

    Using a while loop just isn't necessary in a lot of common usage scenarios (and is not "pythonic").


    Here's one comparison from a mailing list post that I though was a good illustration, too:

    > 2. I know Perl is different, but there's just no equivalent of while
    > ($line = ) { } ?

    Python's 'for' loop has built-in knowledge about "iterable" objects, and that includes files. Try using:

    for line in file:
        ...
    

    which should do the trick.

提交回复
热议问题