Python for loop paired with else traps

Source: Internet
Author: User
Tags terminates

Suppose you have the following code:

 for  in range:    if i = = 5        :print'found it! i =%s ' % ielse:    print'notfound it ... '

The result you expect is that when found 5 o'clock print out:

Found it! i = 5

The results are actually printed as:

Found it! i = 5 not found it ...

Obviously this is not the result we expect.

According to the official documentation:

>when the items are exhausted (which isImmediately when the sequence isEmpty), the suiteinchTheElseClauseifPresent isExecuted andThe loop terminates.>a BreakStatement executedinchThe first suite terminates the loop without executing theElseClause ' s suite. AContinueStatement executedinchThe first suite skips the rest of the suite andContinues with the next item,orWith theElseClauseifthere was no next Item.https:Docs.python.org/2/reference/compound_stmts.html#the-for-statement

The main idea is that when an iteration of an object is iterated and empty, the clause at else is executed, and if a break is included in the For loop, the loop is terminated, and the ELSE clause is not executed.

So the correct wording should be:

 for  in range:    if i = = 5:        print'found it! i =%s  ' % i        breakElse:    print' not found it ... '

When you use Pylint to detect code, you are prompted

 break statement (useless-else-on-loop)

So it is necessary to develop the habit of using Pylint to detect code, and it is difficult to notice such logic errors.

MMM ~

Reprinted from: https://www.cnblogs.com/dspace/p/6622799.html

Python for loop paired with else traps

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.