Python for Else statement

Source: Internet
Author: User

Else statements in the Python loop

Most programming languages have conditional judgments, such as if ... else, in the larger language, else is usually only present in the conditional judgment statement, with the IF statement, but in Python, the else can appear in the for, WHI, as well as the IF condition judgment. In a circular statement such as Le.

Let's look at an example:

12345678910 s = ["a111", "b222", "c333", "d444", "e555"]found = Falsefor c in s:    if c.startswith("c"):        found = True        print u"发现以字母c开头的项"        breakif not found:    print u"没有发现以字母c开头的项"

Do a loop, and if you find a letter that satisfies the condition, print out a hint, and then print out another message if you don't see it in the loop. We need to set an additional variable to record whether the target character (the found variable in the program) is found, and then make an if judgment after the loop is complete.

The above notation is certainly possible, but if we use the Else statement in the loop, the code will be more concise and clear. Like what:

1234567 s = ["a111", "b222", "c333", "d444", "e555"]for c in s:    if c.startswith("c"):        print u"发现以字母c开头的项"        breakelse:    print u"没有发现以字母c开头的项"

In this case, it is not necessary to record the additional variables that are found, and it is no longer necessary to make the If judgment after the loop is completed, but the effect is the same as the first code.

In Python, for ... else means that the statement in for is no different from normal, while the statement in else is executed when the loop is executed normally (that is, for not breaking out by break), while ... else is the same.

If you replace break with continue, the effect is that the statement in else is definitely executed, and some occasions are an interesting usage.

Python for Else statement

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.