Describes the usage of loop statements in Python, and details about python
I. Introduction
The conditions and loop statements of Python determine the program control flow and reflect the diversity of structures. It should be important to understand that if, while, for, and the else, elif, break, continue, and pass statements that work with them.
Ii. Details
1. if statement
The if clause in Python consists of three parts: the keyword itself, the conditional expression used to determine whether the result is true or false, and the code block executed when the expression is true or not. The syntax of the if statement is as follows:
if expression: expr_true_suite
The expr_true_suite code block of the if statement is executed only when the Boolean value of the result of the conditional expression is true. Otherwise, the statement following the code block is executed.
(1) multiple conditional expressions
A single if statement can use the boolean operators "and", "or" and "not" to implement multiple or negative conditions.
(2) code block of a single statement
If the code block of a composite Statement (such as the if clause, while, or for loop) contains only one line of code, it can be written on the same line as the preceding statement. For example, if make_hard_copy: send_data_to_printer (), such a single-line statement is legal. Although it may be convenient, it makes the code more difficult to read, therefore, we recommend that you move this line of code to the next line and indent it properly. Another reason is that if you need to add new code, you still have to move it to the next line.
2. else statements
Python provides the else statement used together with the if statement. if the Boolean value of the conditional expression of the if statement is false, the program executes the code after the else statement. The syntax is as follows:
if expression: expr_true_suiteelse: expr_false_suite
In C, else statements are not found out of the scope of condition statements, but different from Python, else statements can be used in the while and for loops, the else clause is executed only after the loop is completed, that is, the break statement also skips the else block.
For example, the maximum number of values between 10 and 20 is displayed.
View the CODE piece derived from my CODE piece on CODE
#!/usr/bin/env python def showMaxFactor(num): count = num / 2 while count > 1: if (num % count == 0): print 'largest factor of %d is %d' % (num, count) break count = count - 1 else: print eachNum, 'is prime' for eachNum in range(10, 21): showMaxFactor(eachNum)
View the CODE piece derived from my CODE piece on CODE
largest factor of 10 is 5 11 is prime largest factor of 12 is 6 13 is prime largest factor of 14 is 7 largest factor of 15 is 5 largest factor of 16 is 8 17 is prime largest factor of 18 is 9 19 is prime largest factor of 20 is 10
3. elif (else-if) Statement
Elif is an else-if statement of Python. It checks whether multiple expressions are true and executes the code in a specific code block when the expressions are true. Like else, The elif statement is optional. However, the difference is that the if statement can have at most one else statement, but can have any number of elif statements.
if expression1: expr1_true_suiteelif expression2: expr2_true_suite ...elif expressionN: exprN_true_suiteelse: none_of_the_above_suite
In the future, Python may support switch/case statements, but it can be simulated using other Python structures. In Python, a large number of if-elif statements are not difficult to read.
View the CODE piece derived from my CODE piece on CODE
if user.cmd == 'create': action = "create item" elif user.cmd == 'delete': action = 'delete item' elif user.cmd == 'update': action = 'update item' else: action = 'invalid choice... try again!'
The preceding statement can also be simplified using sequence and member relationship operators:
View the CODE piece derived from my CODE piece on CODE
if user.cmd in ('create', 'delete', 'update'): action = '%s item' % user.cmd else: action = 'invalid choice... try again!'
You can also use the Python dictionary to provide more elegant solutions, using ing objects (such as dictionaries) the biggest benefit is that its search operations are much faster than sequential queries like statements or for loops.
View the CODE piece derived from my CODE piece on CODE
msgs = {'create': 'create item', 'delete': 'delete item', 'update': 'update item' } default = 'invalid choice... try again!' action = msgs.get(user.cmd, default)
4. conditional expressions (that is, "ternary operators ")
The syntax of the ternary operator is: X if C else Y. You only need one row to complete the condition judgment and value assignment operations:
View the CODE piece derived from my CODE piece on CODE
>>> x, y = 4, 3 >>> smaller = x if x < y else y >>> smaller 3
5. while statement
While is a conditional loop statement. Compared with the if statement, if the condition after if is true, a corresponding code block is executed. While the code block in the while statement will be executed cyclically until the loop condition is no longer true.
(1) General syntax
The syntax of the while loop is as follows:
while expression: suite_to_repeat
The while LOOP suite_to_repeat clause is executed cyclically until the expression value is Boolean false.
(2) counting cycle
count = 0while (count < 9): print 'the index is:', count count += 1
The code block contains print and auto-increment statements, which are repeatedly executed until count is no less than 9. The index count is printed during each iteration and then increases by 1.
(3) infinite loop
while True: handle, indata = wait_for_client_connect() outdata = process_request(indata) ack_result_to_client(handle, outdata)
An infinite loop will never end, but it is not necessarily a bad thing. Many Communication Server Client/Server systems work through it.
6. for statements
Another Loop Mechanism provided by Python is the for statement, which is the most powerful loop structure in Python. It can traverse sequence members and can be used in list parsing and generator expressions. It automatically calls the next () method of the iterator, capture the StopIteration exception and end the loop (all of this happens internally ). Python for is more like a foreach loop in shell or script language.
(1) General syntax
The for loop accesses all elements in an iteratable object (such as a sequence or iterator) and ends the loop after all entries are processed. Its syntax is as follows:
For iter_var in iterable:
Suite_to_repeat
In each loop, the iter_var iteration variable is set as the current element of the iteration object (sequence, iterator, or other objects that support iteration) and is available to the suite_to_repeat statement block.
(2) used for sequence type
A for loop can iterate different sequence objects, such as strings, lists, and tuples.
There are three basic methods for iterative sequences:
Iteration by sequence items
View the CODE piece derived from my CODE piece on CODE
>>> nameList = ['Walter', "Nicole", 'Steven', 'Henry'] >>> for eachName in nameList: ... print eachName, "Lim" ... Walter Lim Nicole Lim Steven Lim Henry Lim
Iterates a list .. Each iteration, the eacgName variable is set to a specific element in the list.
Iterative by sequential Index
View the CODE piece derived from my CODE piece on CODE
>>> nameList = ['Cathy', "Terry", 'Joe', 'Heather','Lucy'] >>> for nameIndex in range(len(nameList)): ... print "Liu,", nameList[nameIndex] ... Liu, Cathy Liu, Terry Liu, Joe Liu, Heather Liu, Lucy
Instead of iteration elements, it iterates through the index of the list. However, direct iterations are faster than index iterations.
Usage and index Iteration
View the CODE piece derived from my CODE piece on CODE
>>> nameList = ['Donn', 'Shirley', 'Ben', 'Janice','David', 'Yen', 'Wendy'] >>> for i, eachLee in enumerate(nameList): ... print "%d %s Lee" % (i+1, eachLee) ... 1 Donn Lee 2 Shirley Lee 3 Ben Lee 4 Janice Lee 5 David Lee 6 Yen Lee 7 Wendy Lee
(3) used for iterator type
The method of using the for loop to access the iterator is similar to that of the access sequence. The iterator does not represent the set of loop entries. The iterator object has a next () method, and the next entry is returned after the call. After all the entries have been iterated, The iterator raises a StopIteration exception to tell the program that the loop ends. The for statement calls next () internally and captures exceptions.
The code that uses the iterator for A for loop is almost identical to the code that uses a sequence entry. In fact, in most cases, it is impossible to determine whether an iteration is a sequence or an iterator. Therefore, when traversing an iterator, it may actually mean traversing a sequence, iterator, or an object that supports iteration (it has the next () method ).
(4) range () built-in functions
The built-in function range () can convert a for loop similar to foreach into a more familiar statement.
Python provides two different methods to call range (). The complete syntax requires two or three Integer Parameters: range (start, end, step = 1), range () A list containing all k is returned, where start <= k <end, from start to end, and k increments ste each time. The step cannot be zero. Otherwise, an error will occur.
View the CODE piece derived from my CODE piece on CODE
>>> range(3, 7) [3, 4, 5, 6] >>> for eachVal in range(2, 19, 3): ... print "value is:", eachVal ... value is: 2 value is: 5 value is: 8 value is: 11 value is: 14 value is: 17
Range () has two simple syntax formats: range (end) and range (start, end ). Start is 0 by default, and step is 1 by default.
(5) xrange () built-in functions
Xrange () is similar to range (), but xrange () may be more suitable for a large range list because it does not create a full copy of the list in the memory. It is used only in the for loop, and it does not make sense to use it outside the for loop. Its performance is much higher than range () because it does not generate the entire list. In future versions of Python, range () may return an iterator like xrange () (neither a list nor an iterator ).
(6) sequence-related built-in functions
Sequence-related functions: sorted (), reversed (), enumerate (), and zip () are called "sequence-related" because of the two functions (sorted () and zip ()) returns a sequence (list), and the other two functions (reversed () and enumerate () return the iterator (similar sequence ).
7. break and continue statements
The break statement in Python can end the current loop and jump to the next statement, similar to the break in C. It is often used when an external condition is triggered (usually through the if statement check) and needs to exit from the loop immediately .. The break statement can be used in the while and for loops.
The continue statement in Python is no different from the traditional continue statement in other advanced languages. It can be used in the while and for loops. While loop is a condition
While the for loop is iterative, so continue must meet some prerequisites before starting the next loop, otherwise the loop ends normally.
When the program encounters a continue statement, the program terminates the current loop, ignores the remaining statements, and then returns to the top of the loop. Before starting the next iteration, if it is a conditional loop, We will verify the conditional expression. If there is an iteration loop, it verifies whether there are still elements that can be iterated. The next iteration starts only when the verification is successful.
View the CODE piece derived from my CODE piece on CODE
#!/usr/bin/env python valid = False count = 3 passwdList=('abc',) while count > 0 and valid == False: input = raw_input("enter password:").strip() # check for valid passwd for eachPasswd in passwdList: if input == eachPasswd: valid = True break if not valid: # (or valid == 0) print "invalid input" count -= 1 continue else: break
While, for, if, break, and continue are used in combination to verify user input. The user has three chances to enter the correct password to prevent the user from guessing the password.
8. pass statement
Python does not contain empty braces or semicolons (;) to indicate that "nothing is done" in C. If you need to write no statements in the substatement block, the interpreter prompts a syntax error. Therefore, Python provides the pass statement, which does not do anything, that is, NOP (No OPeration). pass can also be used as a small skill in development to mark the code to be completed in the future.
Def foo_func ():
Pass
Such a code structure is useful in development and debugging, because the structure may need to be fixed before writing the code, but it is not expected to interfere with other completed code, it would be a good idea to put a pass where you don't need it to do anything. In addition, it is also frequently used in exception handling. For example, you track a non-fatal error and do not want to take any measures.
9. iterator and iter () Functions
(1) What is an iterator?
The iterator provides a class sequence interface for the class sequence object. You can use their indexes to "iterate" from 0 to the last entry of the series, it is very easy to use the "count" method to iterate the sequence. Python iterations seamlessly support sequence objects and allow programmers to iterate non-sequence types, including user-defined objects.
The iterator is very clever to use. It can iterate objects that are not sequences but show sequence behavior, such as Dictionary keys and lines of a file. When an object entry is iterated cyclically, you do not have to worry about whether it is an iterator or a sequence.
(2) Why the iterator?
Definition of iterator: Provides extensible iterator interfaces, improves the performance of list iterations, improves the performance of dictionary iterations, and creates real iteration interfaces, instead of accessing the original random object, backward compatibility with all existing user-defined classes, extended simulated sequences and ing objects, and iterative non-sequential sets (such as mappings and files, you can create more concise and readable code.
(3) how to iterate
The iterator has an object of the next () method, instead of counting through indexes. When a Loop Mechanism (such as a for statement) requires the next item, the next () method of the iterator can be called to obtain it. After all entries are retrieved, A StopIteration exception is thrown. This does not indicate an error, but indicates that the external caller has finished iteration.
However, the iterator has some limitations. For example, you cannot move backward, return to the start, or copy an iterator. If you want to iterate the same object again (or at the same time), you can only create another iterator object. However, there are other tools to help you use the iterator.
The reversed () built-in function returns an iterator for reverse access. The built-in functions of enumerate () also return the iterator. The other two new built-in functions are any () and all (). If the values of one or all entries in the iterator are Boolean, the return values are true.
(4) use the iterator
Sequence
View the CODE piece derived from my CODE piece on CODE
>>> myTuple = (123, 'xyz', 45.67) >>> i = iter(myTuple) >>> i.next() 123 >>> i.next() 'xyz' >>> i.next() 45.670000000000002 >>> i.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
In a for loop, for I in seq: do_something_to (I) automatically calls the next () method of the iterator and monitors StopIteration exceptions.
Dictionary
The dictionary and file are two other iteratable Python data types. The dictionary iterator traverses its key (keys). The statement for eachKey in myDict. keys () can be abbreviated as for eachKey in myDict.
Python also introduces three new built-in dictionary methods to define iteration: myDict. iterkeys () (iterated by keys), myDict. itervalues () (iterated through values) and myDicit. iteritems () (iterations through key/value pairs ). Note: The in operator can also be used to check whether the dictionary key exists. The Boolean expression myDict. has_key (anyKey) can be abbreviated as anyKey in myDict.
File
The iterator generated by the file object automatically calls the readline () method. In this way, the loop can access all rows of the text file. You can replace for eachLine in myFile with for eachLine in myFile. readlines ().
(5) variable objects and iterators
It is not a good idea to modify variable objects during iteration, which is a problem before the occurrence of the iterator. The iterator of a sequence only records the elements that have arrived at the moment. Therefore, if an element is changed during iteration, the update will immediately reflect the entries in your iteration. The dictionary cannot be changed when the key of the dictionary is iterated. The keys () method of the dictionary is acceptable, because keys () returns a list independent of the dictionary, and the iterator is bound with the actual object, it will not continue.
(6) how to create an iterator
Call iter () on an object to obtain its iterator. Its syntax is as follows: iter (obj) or iter (func, sentinel ). If you pass a parameter to iter (), it will check whether you pass a sequence. If so, it will iterate from 0 to the end of the sequence based on the index. Another method to create an iterator is to use a class. A class that implements the _ iter _ () and next () methods can be used as the iterator. If two parameters are passed to iter (), it repeatedly calls func until the next value of the iterator is sentinel.
10. List Parsing
List parsing (list comprehensions or scaled down to List comps) comes from the functional programming language Haskell. It is a very useful, simple, and flexible tool that can be used to dynamically create a list.
Function programming features supported by Python, such as lambda, map (), and filter (), can be simplified to a list parsing statement through list parsing. Map () applies an operation to all list members. filter () filters list members based on a conditional expression. lambda () allows you to quickly create function objects with only one row.
Syntax of list parsing: [expr for iter_var in iterable], which iterates all entries of the iterable object. The expr is applied to each member of the sequence. The final result value is the list generated by the expression, and the iteration variable does not need to be part of the expression.
View the CODE piece derived from my CODE piece on CODE
>>> [x ** 2 for x in range(6)] [0, 1, 4, 9, 16, 25]
The list parsing expression can replace the built-in map () function and lambda function, and is more efficient. Combined with the if statement, list parsing also provides an extended version Syntax: [expr for iter_var in iterable if cond_expr], during iteration, it filters/captures sequence members that meet the condition expression cond_expr.
Select the odd number in the sequence:
View the CODE piece derived from my CODE piece on CODE
>>> seq = [11, 10, 9, 9, 10, 10, 9, 8, 23, 9, 7, 18, 12, 11, 12] >>> filter(lambda x: x % 2, seq) [11, 9, 9, 9, 23, 9, 7, 11] >>> [x for x in seq if x % 2] [11, 9, 9, 9, 23, 9, 7, 11]
Even if filter () and lambda are not used, you can use list parsing to complete the operation and obtain the desired number.
Matrix example: iterate a matrix with three rows and five columns, [(x + 1, y + 1) for x in range (3) for y in range (5)].
Disk File example: if there is a data file text.txt, You need to calculate the number of all non-blank characters, you can split each line into words, and then calculate the number of words: >>> f = open('hhga.txt ', 'R'); len ([word for line in f for word in line. split ()]). Quickly calculate the file size: >>> import OS + OS .stat('text.txt '). st_size. Add the length of each word: >>> f. seek (0); sum ([len (word) for line in f for word in line. split ()]).
11. Generator expression
The generator expression is an extension of list parsing. You can create a list containing specific content with only one line of code. Another important feature is the generator. The generator is a specific function that allows a value to be returned, and then "pause" the code execution and resume it later.
One disadvantage of list Parsing is that all data must be generated to create the entire list. This may have a negative effect on the iterator with a large amount of data. The generator expression solves this problem by combining list parsing with the generator.
Generator expressions are very similar to list parsing, and their basic syntax is basically the same. However, it does not actually create a number list, but returns a generator. After calculating an entry, the generator "generates" the entry (yield. The generator expression uses lazy evaluation, which is more effective in memory usage. The generator does not discard list parsing. It only uses a more user-friendly structure of memory. Based on this, there are many places where the generator is used.
List parsing Syntax:
[expr for iter_var in iterable if cond_expr]
Generator expression syntax:
(expr for iter_var in iterable if cond_expr)
Disk File example: calculate the total number of non-blank characters in a text file. If the size of this file is large, the memory performance of this line of code will be very low, because you want to create a long list to store the length of words. To avoid creating a large list, use the generator expression to complete the sum operation. The optimized code >>> sum (len (word) for line in data for word in line. split () is to delete square brackets, two bytes less, and more memory saving.
Cross-pairing example: the generator expression is like a lazy list parsing (which has become its main advantage). It can also be used to process other lists or generators, such as x_product_pairs = (I, j) for I in rows for j in cols ()).
Example of refactoring to find the longest row of the file:
Previous methods:
View the CODE piece derived from my CODE piece on CODE
#!/usr/bin/env python def fun(): f = open('/etc/motd', 'r') longest = 0 allLines = [x.strip() for x in f.readlines()] #or allLineLens = [len(x.strip()) for x in f] f.close() for line in allLines: linelen = len(line) if linelen > longest: #or longest = max(allLineLens) longest = linelen return longest
New method:
Use the generator expression to replace the list parsing and max () functions, and remove the file opening mode (read by default): return max (len (x. strip () for x in open ('/etc/motd ')).
Iii. Summary
(1) The itertools module is added to support the application of the iterator. List parsing and expression generation can be combined with instance analysis.
(2) If there are any deficiencies, please leave a message. Thank you first!