Python--while and for Loops

Source: Internet
Author: User
Tags unpack

While loop general format: [python] View plain copywhile <test>: <statements1> else <test>: <statements2 > Else is an optional part that executes when control leaves the loop without encountering a break statement. [Python] View plain copy>>> x = ' spam ' >>> while x:print (x,end= ') x = x[1:] Spa M Pam am M Note: Use the end = ' keyword parameter here to make all output appear on the same line, Separated by a space------------------------------------------------------------------------------------------------------------------ ------------------------------break, continue, pass, and loop Elsebreak: Jump out of the nearest loop (skip the entire loop statement) Continue: Jumps to the beginning of the nearest loop (to the first line of the loop) pass: Do nothing, Just an empty placeholder statement loop Else BLOCK: Executes only when the loop is normally gone (that is, no break statement is encountered)---------------------------------------------------------------------------- --------------------------------------------------------------------the general loop format joins break and continue, the general loop format of while is changed to: [ Python] View plain copywhile <test1>: <statements1> if <test2>:break if <test3>:con Tinue Else: <statements2>----------------------------------------------------------------------------------------------------------------------------------------------- The-pass statement is a placeholder statement that has no operations and can be used when the syntax requires a statement and no statement is writable. It is typically used to write an empty body for a compound statement. For example, if you want to write an infinite loop, and do nothing for each iteration, write a pass[python] view plain copy>>> while True:p. Because the subject is just an empty statement, Python is trapped in a dead loop, This program is not useful. You will see more meaningful use of it in the future. For example, ignoring the exceptions caught by the try statement and defining an empty class object with attributes, the class implements object behavior like the structure and record of other languages. Pass sometimes means "will be filled in later", only temporarily used to fill function body [python] View plain copydef func1 (): Pass Def FUNC2 (): Pass We can't keep the function body empty without producing syntax Error, so you can use pass instead of "another: three points can be used in a program after Python3.0 ... Instead of pass, it seems more concise and clear "------------------------------------------------------------------------------------------- -----------------------------------------------------The continue statement jumps immediately to the top of the loop, skipping the loop, and executing the next loop break statement immediately leaves the loop [python ] View plain copy>>> while true:name = input (' Enter name: ') if name = = ' Stop ': break age = Input (' Enter Age: ') print (' Hello ', name, ' = = ', int (age) **2) Enter Name:gavin Enter age:2 Hello Gavin = 4 Ent ER Name:spam Enter age:20 Hello Spam = $ enter Name:stop-------------------------------------------------------- When the----------------------------------------------------------------------------------------loop else and the loop else clause are combined, The break statement can often ignore the search status flags that are required in other languages.          For example, the following program searches for a factor greater than 1 to determine whether positive integer y is a prime number: [Python] View plain copy>>> def judge (y): x = Y//2 while x >1: If y% x ==0:print (y, ' have factor ', X) break X-= 1 else:print (y, ' is PRI  Me ') >>> judge (8) 8 has factor 4 >>> judge (+) is Prime >>> judge (119) 119 Has factor 17 in addition to setting the flag bit at the end of the loop to test, you can also insert a break when a factor is found. In this way, the loop else clause can be considered to be executed only if no factor is found. If you do not encounter break, the number is prime. Note that when you first determine if the while loop condition is not satisfied, that is, if a loop is not in progress, or if the ELSE clause is executed, the ========================================================== =======================for Loop general usage: [python] View plain copyfor <target> in <object>: <statements> el SE: <statements> when Python runs For loops, the elements in the sequence object are assigned to the target individually, and then the loop body is executed for each element. The For loop can also be in the complete format of the break, continue, and ELSE clauses as follows: [Python] View plain copyfor <target> in <object>: <statements&gt      ; If <test>:break if <test>:continue else: <statements>-------------------------------------- ----------------------------------------------------------------------------------------------------------Basic applications: [Python] View plain copy>>> for x in [' Spam ', ' eggs ', ' ham ']: print (x,end= ') spam eggs ham two examples below The child calculates the list to get the sum and the product of all the elements. [Python] View plain copy>>> s = 0 >>> for x in [1,2,3,4]: S + = x >>> x #这里x这个变量          Still has a value of 4 >>> s [python] view plain copy>>> p = 1 >>> for x in [1,2,3,4]: P *= x >>> P 24 Later, you will know that Python has some tools that can automatically apply operations like ' + ' and ' * ' to the elements in the list, but using a for loop is usually as simple------------------------------- -----------------------------------------------------------------------------------------------------------------other data types are not only applicable to lists, for loops apply to any sequence, and for loops can also be applied to strings and tuples, which is not an example. In fact, a for loop can even be applied to objects that are not sequences at all, and are valid for files and dictionaries. --------------------------------------------------------------------------------------------------------------- ---------------------------------tuple assignment in a for loop [Python] View plain copy>>> T = [(UP), (3,4), (5,6)] >> > for (A, B) in T:print (A, B) 1 2 3 4 5 6 [Python] View plain copy>>> for x in T:print ( x) (1, 2) (3, 4) (5, 6) Note the difference between the two examples above. The first example can be seen as the assignment operation of a tuple's unpacking, which is usually used in conjunction with the ZIP call we're going to introduce to implement parallel traversal. In Python, it is usually also used with SQL databases, where the query results table is returned as a sequence of sequences used here--the outer list is the database table, the nested tuples are the rows in the table, the tuple assignments and columns correspond to the FOR Tuples in the loop make it convenient to use the items method to traverse the keys and values in the dictionary without having to traverse the keys and manually index them to get the values: [Python] View plain copy>>> D = {' A ': 1, ' B ': 2, ' C ': 3} > >> for key in D:print (key, ' = = ', D[key]) b = 2 c = 3 A = 1 [python] View plain COPY&G T;>> list (D.items ()) [(' B ', 2), (' C ', 3), (' A ', 1)] >>> for (key,value) in D.items (): PrinT (key, ' = = ', value) b = 2 c = 3 A = 1 It is important to note that the tuple assignment in the For loop is not a special case; any assignment target after the word for is syntactically valid. Although we always assign values manually in the For loop to unpack: [Python] View plain copy>>> for both in t:a,b = both print (A, b) 1 2 3 4 5 6----------------------------------------------------------------------------------------------------------- -------------------------------------Python3.0 the sequence to be extended in the For loop actually, the loop variable in the For loop can really be any assignment target, here, You can also use Python3.0 's extended sequence to unpack the assignment syntax to extract the elements and parts of a sequence in a sequence. Extended sequence assignment can be referenced here------------------------------------------------------------------------------------------------------------- -----------------------------------nested for Loop This code searches the object list for each key and reports its search results: [python] View plain copy>>> items = [' AAA ', 111, (4,5), 2.01] >>> tests = [(4,5), 3.14] >>> for key in Tests:for item in ITEMS:I              F key = = Item:print (key, ' was found ') "Break Else:print" (Key, ' not found ') (4, 5) was found 3.14 not fOund ================================================================================= Tips for writing loops 1. The built-in range function returns a series of consecutive incremented integers that can be used as index 2 in for. The built-in zip function returns a list of tuples of parallel elements that can be used to traverse the entire sequence within for. --------------------------------------------------------------------------------------------------------------- ---------------------------------Loop counter: The while and rangerange functions are common tools that can be used in a variety of environments, although the range is common in the for loop to produce an index. But it can also be used in any place that requires an integer list. In Python3.0, Range is an iterator that produces elements as needed, so we need to include them in a list call to display their results one time: [Python] View plain copy>>> list (range (5 ), List (range (2,5)), List (range (0,10,2)) ([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8]) A parameter, range produces a zero-based list of integers, but does not include the parameter's value; If two arguments are passed, the first one is considered the bottom boundary. The third selection parameter provides a step value that, when used, adds a stepping value to each successive integer (the stepping value defaults to 1). Range can also be non-positive or not incrementing: [Python] View plain copy>>> list (range ( -5,5) [ -5, -4, -3,-2,-1, 0, 1, 2, 3, 4] >>> list (range (5,-5,-2)) [5, 3, 1,-1,-3] from the internal implementation point of view, the for loop is used in this way, The details of the iteration are automatically processed. If you really want to control the index logic explicitly, you can do it with a while loop: [Python] View plain copy>>> s = ' gavin ' >>> i = 0 &GT;&GT;> while I<len (s): print (S[i],end = ") i+=1 g A V i n-------------------------------------------- ----------------------------------------------------------------------------------------------------non-exhaustive traversal: range and sharding in general , it is best to use a simple for loop in Python, do not use while, and do not use the range call in a For loop, just as a last resort when traversing a sequence. [Python] View plain copy>>> for item in X:print (item) However, the usefulness of using range for indexing is that we can implement a special traversal by controlling the range, for example, Skipping elements during traversal [Python] View plain copy>>> S = ' abcdefghijklmn ' >>> for I in Range (0,len (S), 2):p rint (S[i] , end = ") A c e g I k m here we access every other element in the string s through the resulting range list, to use every two elements, you can change the third parameter of range to 3, and so on. However, this may not be the best technique to implement in Python today, and if you really want to skip the elements in the sequence, you can use a shard expression in the form of the third limiting value of the extension described earlier, for example, to use every other string in S, you can use the step value and the second shard: [Python] View Plain copy>>> for item in S[::2]:p rint (item,end= ") A C e g I k m the result is the same, but it's easier for us to write and easier for others to read. --------------------------------------------------------------------------------------------------------------- ---------------------------------Modify list: A common scenario in which range can use a combination of range and for is to modify the list as it is traversed in a loop. For example, suppose you want to add 1 to each element of the list for some reason, you can do it through a simple for loop, but the result may not be what you want: [Python] View plain copy>>> L = [1,2,3,4,5] >> > For x in L:x+=1 >>> l [1, 2, 3, 4, 5] >>> x 6 This does not work because it modifies the loop variable x instead of the list L. To really walk through the columns in our table when it is modified, we need to use the index so that we can assign an updated value to each location over the duration. The Range/len combination can produce the required index for us. [Python] View plain copy>>> L = [1,2,3,4,5] >>> for I in range (len (L)): L[i] +=1 >> > L [2, 3, 4, 5, 6] can also be done with a while loop, but it is slower to run. [Python] View plain copy[x+1 for x in L] This form of list-resolution expressions can do similar work, and there is no modification of the original list in place (we can assign the new list object of the expression to L, However, this does not update any of the other reference values of the original list. Because this is the core concept of the loop, we will make a complete introduction to the list parsing later. --------------------------------------------------------------------------------------------------------------- ---------------------------------Parallel traversal: The zip and map built-in zip functions let us use a for loop to use multiple sequences in parallel, and in the basic operation, the zip gets one or more sequences as parameters, and then returns a list of tuples, Match the elements of these sequences into pairs for example, suppose we want to use two lists: [Python] View plain copy>>> A = [1,2,3,4] >>> B = [11,22,33,44] to merge the elements in these lists, we can use a zip to create a list of tuple pairs (like range, Zip is also an iterative object in Python3.0, so we have to include it in a list call to display all results at once) [Python] View plain copy>>> C = Zip (A, b) >> > C <zip Object at 0x0405be18> >>> list (c) [(1, 11), (2, 22), (3, 33), (4, 44)] Such results are also useful in other environments, but with F   or loop, it supports parallel iterations: [Python] View plain copy>>> for (x, y) in Zip (A, B): print (x, y, '---', x+y) 1---12 2---3---4---the zip can accept any type of sequence (in fact, any object that can be iterated, including files), and can have more than two parameters. For example [Python] View plain copy>>> t1,t2,t3 = (All-in-all), (4,5,6), (7,8,9) >>> T2 (4, 5, 6) >>> list (Z  IP (T1,T2,T3)) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] when the parameter length is not the same, the zip truncates the resulting tuple with the length of the shortest sequence: [Python] View plain copy>>> S1 = ' abc ' >>> S2 = ' xyz123 ' >>> list (Zip (S1,S2)) [(' A ', ' X '), (' B ', ' Y '), (' C ', ' Z ')]--------------- --------------------------------------------------------------------------------------------------------------- ------------------used the zip construction dictionary, as described earlier, when the collection of keys and values must be evaluated at run time, the zip call used here can also be used to produce a dictionary, and is very handy. Suppose you have the following list of keys and values: [Python] view plain copy>>> keys = [' spam ', ' eggs ', ' toast '] >>> vals=[1,2,3] Turn these lists into dictionaries The practice is to zip up these characters and step through the For loop in parallel: [Python] View plain copy>>> list (Zip (keys,vals)) [(' Spam ', 1), (' Eggs ', 2), (' Toast ', 3)] >>> D2 = {} >>> for (key,val) in Zip (keys,vals): D2[key] = val >>> D2 {' Toast ': 3, ' spam ': 1, ' Eggs ': 2} However, in Python2.2 and later versions, you can skip the for loop completely and pass the zip-over key/value list directly to the built-in Dict constructor: [python] View plain cop y>>> D3 = dict (Zip (keys,vals)) >>> D3 {' Toast ': 3, ' spam ': 1, ' Eggs ': 2}---------------------------- --------------------------------------------------------------------------------------------------------------- -----produce offsets and elements: enumerate, we discussed the use of range to produce offset values for elements in a string, not those at offsets, but in some programs we both need to: the desired element and the offset value of the element.      You can do this in the following simple example: [Python] View plain copy>>> s = ' spam ' >>> offset = 0 >>> for item in s: print (item, ' appears at offset ', offset) offset + = 1 s appears at offset 0 p appears at offset 1 a appears at Offset 2 m appears at offset 3 but the built-in function enumerate can do this for us: [Python] View plain copy>>> S = ' spam ' >>> f  or (Offset,item) in enumerate (s): Print (item, ' appears @ Offset ', offset) S appears at offset 0 p-appears at Offset 1 A appears at offset 2 m appears at offset 3 can see: [Python] View plain copy>>> enumerate (S) <enume Rate object at 0x03602fa8> >>> list (enumerate (s)) [(0, ' s '), (1, ' P '), (2, ' a '), (3, ' M ')] Enumerate function returns a raw Builder object: This object supports the next iteration protocol to learn. In short, this object has a __next__ method that is called by the next built-in function and returns a (Index,value) Ganso at each iteration of the loop. We can unpack tuples in a for loop by tuple assignment (much like using zip) [Python] View plain copy>>> e = enumerate (S) >>> e <enumerate objec T at 0x03602f80> >>> next (E) (0, ' s ') >>> Next (E) (1, ' P ') >>> Next (E) (2, ' a ') [Pyth On] View plain copy>>> [c*i for (i,c) in ENUmerate (S)] [', ' P ', ' AA ', ' mmm ']   

  

Python--while and for Loops

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.