Python Learning notes Loops and Iterations

Source: Internet
Author: User

    • For and while basic syntax
    • Break and Continue
    • else's use
    • Application of enumerate and zip in the loop

For and while basic syntax

The loops in Python are implemented using the for and while statements, with the basic syntax structured as follows:

#while语法
while expression: statements
#for语法 for in s: statements

While an infinite loop executes the statement in the loop body until the correlation expression evaluates to False. The For statement iterates through all the elements in s until there are no elements to iterate over. All objects that can be iterated can use a for statement, and all objects that implement the __iter__ and __next__ methods are iterative objects.

A simple example is as follows:

 for  in range    :print= 0 while 1    :if i <:        print(i    )else:        break 

Break and Continue

Use break to jump out of the loop, and continue can jump to the next iteration of the loop, as in the following example:

Reads a file, encounters a blank line, and stops reading.

 for  in open ("test.txt"):    = line.strip ()    if  not Stripped:         Break #遇到空行, stop reading, terminate the entire loop

  

Reads a file, and then ignores the processing when it encounters a blank line.

 for  in open ("test.txt"):    = line.strip ()    if  not Stripped:         continue #遇到空行, skipping processing, processing the next line

  

The break and Continue statements apply only to the most inner loop that is being executed, and if you want to jump out of a multilayer loop nesting structure, you need to use multiple break and continue or use exceptions. As shown in the following example:

#reads a file, processes a non-blank line, and ends the entire processing if there is a blank character in a non-blank line forLineinchOpen"Test.txt"): Stripped=Line.strip ()if  notStripped:Continue     forCinchStripped:ifC is "':             Break#use exceptions to jump out of the loop forLineinchOpen"Test.txt"): Stripped=Line.strip ()if  notStripped: Break     forCinchStripped:ifC is "':            RaiseRuntimeError ("C is empty"")

Else statement

 

You can also add an else statement after the while and for statement, with the following syntax:

 while expression:    statementselse:    statementsfor in  s:    StatementsElse:    statements

Else will be executed in two cases:

1. The loop does not execute at all, and the Else statement is executed immediately

2. After the loop executes, the Else statement is executed.

NoteIf you use break to jump out of a loop in a loop, the Else statement is not executed. else the main loop technique is followed by a review, which carries out some subsequent processing, such as the ability to close a file. As the following example, we loop a non-blank line from a file, closing the file after the file is read, similar to the use of with.

f = open ("test.txt") for in f.readlines ():    =  Line.strip ()    if not stripped:        continueElse :     Print ("close file")    f.close ()

The use of enumerate and zip in loops

We can only loop through the elements in S if we want to get to the index using the for-in S loop in this way, as follows:

 for inch Range (len (s)):     = S[i]

You can also use the enumerate () function to simplify, enumerate (s) to create an iterator, the return value is a tuple sequence (0,s[0]), (1,s[1]),... (N,s[n]).

 for inch Enumerate (s):     Pass

Another common form of looping is to iterate over more than two sequences at the same time, such as two-length sequences s and T, to handle each of its corresponding items separately, with the code as follows:

 s = [1,2,3,4,5]t  = [10,11,12,14,15 while  i < Len (s) and  i < Len (t): x  = S[i] y  = T[i]  
    
     if 
     x < y:  print  ( " x < y  "  )  else  :  print  ( x >= y   " ) I  + = 1 

You can use the zip () built-in function to simplify this code, as follows:

 for inch Zip (s,t):     if x < y:        print("x < y")      else:        print("x >= y")

Zip (S1,S2...SN) combines sequence s1,s2...sn sequences into one tuple (s1[0],s2[0]...sn[0]),... (S1[n],s2[n]...sn[n]), if the length of the s1,s2...sn is not equal, whichever is the shortest length.

Python Learning Notes loops and iterations

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.