Loop statement (for, while) (i)

Source: Internet
Author: User

2016-12-18

While loop structure;

The while statement is the most common iteration structure in the Python language.

The most complete writing format for the while statement is the first line and the test expression, with the body of one or more column indent statements and an optional else part (control

The right to leave the loop without encountering the break statement). Python will always calculate the beginning of the test, and then execute the statement inside the loop body until the test return value is false.

1  while <test>:           #Loop test2     <statements1>    # Loop Body     3 else:                       #Optional Else4     <statements2>    #  Run If didn ' t exit loop with break

The following example keeps cutting the first character of the string until the string is empty and returns to false. This tests the object directly, rather than using the longer equivalent notation (while!). = '), can be said to be a typical notation.

1 ' spam ' 2  while x:                #while X was notempty3     print (x, end=' ' )4     x = x[1:]         #Strip first character off X

This uses the end= ' keyword parameter so that all outputs appear on the same line, separated by spaces.

Python does not have the so-called "do...until (while)" looping statements in other languages. However, similar functionality can be achieved with a test and break at the bottom of the loop body.

1  while True: 2     ... loop body ... 3     if exittest (): break

Break: Jump out of the nearest loop (skip the entire loop statement);

Continue: Jumps to the beginning of the nearest loop (comes to the first line of the loop);

1 x =2 while x:3     x = x-14     if x% 2! = 0:continue5     print")

Continue should be used with caution.

Equivalent substitution of the above code:

1 x =2 while x:3     x = x-14     if x% 2 = = 0:5         print")

Pass: Nothing is done, just a placeholder statement;

Loop Else BLOCK: Executes only when the loop is normally gone (that is, the break statement is not encountered).

The general format of the while loop after the break and continue statements are added:

 1  while  <test1>:  2  <statements1>3< /span> if  <test2>:break  #  exit loop Now,skip Else  4  if  <test3>:continue  #  go to of Loop now,to test1  5  else  :  6  <statements2> #  run if we didn ' t hit a ' break '  

The break and continue statements can appear anywhere in the while (or for) loop body, but are usually further nested in the IF statement and take corresponding actions according to the dictation condition.

For loop structure:

The For loop is a generic sequence iterator in Python: You can traverse elements within any ordered sequence object. The For statement can be used for strings, lists, tuples, and other built-in objects that can be iterated and can be

A new object created through the class.

The first line of the Python for Loop defines an assignment target (or some target), and the object you want to traverse.

1  for  in <object>:        #Assign object items to target2     <statements>                   #repeated loop body:use target3else:4     <statements>                   #If we didn ' t hits a ' break '

Full format for the FOR loop:

 1  for  <target> in  <object>: #   Assign object items to target  2  <statements>3  if  <test>: break  #  exit loop Now:skip Else  4  if  <test>: continue  #  go to top of the loop now  5  else  :  6  <statements> 
tuple assignment in a for loop

If you iterate over a tuple sequence, the loop target itself can actually be a target ancestor. This is just an example of the assignment operation of the tuple's unpacking. remember that the FOR loop assigns the sequence object element to the target,

Assignment arithmetic works the same everywhere.

t = [(UP), (3,4), (5,6)] for in T:                   #aTuple assignment    at work Print (A, B)

This form is usually called with a zip to implement parallel traversal. In Python, it is also commonly used with SQL databases, where the query results table is returned as a sequence of sequences used here--the outer

Lists are database tables, nested tuples are rows in a table, tuple assignments and columns correspond.

Tuples in for loops are convenient to use the items method to traverse the keys and values in the dictionary without having to traverse the key and manually index them to get the value:

 1  D = { " a   ' : 1, " b   ": 2,"   C   ": 3}  2  for  key in       D:  3  print  (Key, " =>  , D[key]) #  use dict Keys iterator and index  

Note: It is important that a tuple assignment in a for loop is not a special case, and that any assignment target after the word for is syntactically valid. Although we always assign values manually in the For loop to unpack the package:

1 T = [(UP), (3,4), (5,6)]2for in3A,     B = both              # Manual Assignment equivalent 4     Print (A, B)

Any nested sequence structure can be unpacked in this way only because the sequence assignment is so generic:

 for inch [(a), 3), ['xy', 6    ]]: Print (A,B,C)

In later versions of Python3.0, because a sequence can be assigned to a more generic set of names (with a name with an asterisk to collect multiple elements), we can use the same syntax in the For loop to extract

The part of a nested sequence:

1  for inch [(1,2,3,4), (5,6,7,8)]: 2     Print (a,b,c) 3 4 Output Result: 5 1 [2, 3] 46 5 [6, 7] 8

This method can be used to represent multiple columns in a row that represents the data for a nested sequence.

Nesting for loops:

This example is to model the loop ELSE clause and the statement nesting in for. Taking into account the list of objects (elements) and the list of keys (tests), this code searches the object list for each key and reports its search results.

1Items = ["AAA", 111, (4,5), 2.01]2Tests = [(4,5), 3.14]3  forKeyinchTests:4      forIteminchItems:5         ifitem = =Key:6             Print(Key,"was found")7              Break8     Else:Print(Key,"Not found!")9 Ten      One  A Run Results -(4, 5) was found -3.14 notfound!

Because the nested if here will perform a break when the matching result is found, and the loop else clause is determined that if you come here, the search fails. Notice the nesting here. When this code executes, there are two loops running at the same time: outer

The loop scans the list of keys, while the inner loop scans the list of elements for each key. The nesting of the loop else clause is critical, and it is indented to the same level as the first row of the inner for loop, so it is associated with the inner loop (not the If or outer layer).

For).

Note: This example is easier to write if we test the membership with the in operator. Because in will have a stealth scan list to find a match, it can replace the inner loop.

1  forKeyinchTests:2     ifKeyinchItems:3         Print(Key,"was found")4     Else:5         Print(Key,"Not found")6 7     8 Output Result:9(4, 5) was foundTen3.14 notFound

In general, let Python do as much work as possible, based on simplicity and performance considerations.

This example performs a typical data structure task with a for: collecting the same elements in two sequences (strings). This is almost a simple set-intersection routine. After the loop is executed, the list of res references contains the SEQ1 and SEQ2

All the elements found.

1res = []#Start Empty2   forXinchSEQ1:#Scan First Sequence3     ifXinchSEQ2:#Common item?4Res.append (x)#Add to result end5 6 Operation Result:7 Res8['s','a','m']

Loop statement (for, while) (i)

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.