Use the else statement method in the Python loop body, pythonelse

Source: Internet
Author: User

Use the else statement method in the Python loop body, pythonelse

This article discusses Python's... Else and while... Else syntax, which is one of the least commonly used and misunderstood syntax features in Python.

The for and while loops in Python all have an optional else Branch (similar to the if statement and try statement), which is executed after the loop iteration is completed normally. In other words, if we do not exit the loop in any way other than the normal mode, the else branch will be executed. That is, there are no break statements, no return statements, or exceptions in the loop body. Consider a simple (useless) Example:
 

>>> for i in range(5):...   print(i)... else:...   print('Iterated over everything  ')...01234Iterated over everything 

In the above Code, we iterate over range (5) and print each number. Because the loop is completed normally, the else Branch is also executed and the Iterated over everything is printed :). On the contrary, if we use the break statement to terminate the loop, the else branch will not execute:
 

>>> for i in range(5):...   if i == 2:...     break...   print(i)... else:...   print('Iterated over everything  ')...01

Note: although the iteration sequence of the loop is empty, the else branch is still executed. After all, the loop is still completed normally.
 

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

Do not forget that all of the above are also suitable for the while... Else:
 

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

But why !?

A common use case of else statements in a loop is loop search. It is assumed that you are looking for a project that meets certain conditions, and additional processing is required, or an error is generated when no acceptable value is found:
 

for x in data:  if meets_condition(x):    breakelse:  # raise error or do additional processing

If you do not have an else statement, you need to set a flag and check it later to determine whether a value that meets the conditions exists.
 

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 really important, but you must do so in many other languages. But like many other features of Python, else statements can generate more elegant Python-style (Pythonic) code. Without a doubt, The above example uses The else statement to make The code more Zen of Python friendly:

This does not mean that you have to use the else statement in the loop, and you can always use the flag. However, else statements often make the code more elegant and readable. You may think this Pythonic, and make the intention clearer (Hi !), However, others may think this is confusing and redundant! Personally, I insist on using else statements in a loop unless there is another more readable method (I think, for me, code readability 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.