Methods for using the Else statement in the Python loop body

Source: Internet
Author: User
This article discusses Python's for...else and While...else syntax, which is one of the least common and misunderstood grammatical features in Python.

The for and while loops in Python have an optional else branch (like the IF statement and the try statement), which executes after the loop iteration is completed normally. In other words, if we do not exit the loop in any way other than the normal way, then the else branch will be executed. That is, there is no break statement, no return statement, or no exception in the loop body. Consider a simple (useless) example:

>>> for I in range (5): ...   Print (i) ... else:   ... Print (' iterated over everything  

In the above code, we iterate over range (5) and print each number. Because we let the loop complete normally, the Else branch is also executed and prints out the iterated over everything:). Conversely, if we terminate the loop with the break statement, then the Else branch will not execute:

>>> for I in range (5): ...   if i = = 2: ...     Break ...   Print (i) ... else:   ... Print (' iterated over everything  ') ... 01

Note that although the sequence of iterations of the loop is empty, the Else branch will still be executed, after all, the loop is still complete normally.

>>> for i in []: ...   Print (i) ... else:   ... Print (' Still iterated over everything (i.e. nothing) ') ... Still iterated over everything (i.e. nothing)

Also do not forget that all of the above are also adapted to While...else:

>>> i = 0>>> while I <= 5:   ... i + = 1   ... Print I ... else:   ... print ' Yep ' ... 12345Yep

But, why?

Another common use case for the Else statement in a loop is to implement a circular lookup. The hypothesis is that you are looking for a project that satisfies a specific condition (item), requires additional processing, or generates an error if an acceptable value is not found:

For x in data:  if Meets_condition (x):    breakelse:  # Raise error or do additional processing

Without the Else statement, you need to set a flag and then detect it later to determine if there is a value that satisfies the condition.

Condition_is_met = FalseFor x in data:  if Meets_condition (x):    Condition_is_met = True if not Condition_is_met:
  # raise error or do additional processing

This is not a really important thing, and in many other languages you have to do so. But like many other features of Python, else statements can produce more elegant Python-style (pythonic) code. No doubt, in the above example, using the Else statement makes the code more the Zen of Python-friendly:

This is not to say that you have to use the Else statement in the loop, you can always use flags and so on. But else statements can often make code more elegant and more readable. You may think this is pythonic, and make the intentions clearer (hi!), yet others may think this is confusing and redundant! Personally, I insist on using the Else statement in the loop, unless there is another more readable method (I think, for me, the readability of the code is the most important).

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.