else in the Python loop that you don't know

Source: Internet
Author: User
In many languages, if else is a combination of conditions, but there are more places in Python where else is used, such as loop for, or while can be combined with else.

Here is a brief introduction to For-else While-else combination

In the case of the else execution in the loop combination, the loop ends normally (that is, it is not exited with break). such as the following code:

numbers = [1,2,3,4,5]for N in Numbers:    if (n > 5):        print (' The value is%d '% (n))        Breakelse:    print (' The For loop does not end with break ')     i = 0while (Numbers[i] < 5):    print (' The index%d value is%d '% (I, numbers[i])    if (Numbers[i] < 0): Break    i = i + 1else:    print (' The loop does not end with break ')   numbers = [ 1,2,3,4,5]for N in numbers:    if (n > 5):        print (' The value was%d '% (n))        Breakelse:    print (' The For loo P does not end with break ')    i = 0while (Numbers[i] < 5):    print (' The index%d value is%d '% (I, numbers[i])) 
  if (Numbers[i] < 0):        break    i = i + 1else:    print (' The loop does not end with break ')

The results of the implementation are as follows:

C:\python27>python.exe for_else.pythe for loop does not end with Breakthe index 0 value is 1the index 1 value is 2the I Ndex 2 value is 3the index 3 value was 4the loop does not end with break
  • 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.