Explain the use of circular statements in Python

Source: Internet
Author: User
First, Introduction

The conditions and circular statements of Python determine the control flow of the program and embody the diversity of the structure. It is important to understand, if, while, for, and the else, elif, break, continue, and pass statements that match them.
Second, detailed
1. If statement

The IF clause in Python consists of three parts: the keyword itself, the conditional expression used to determine the authenticity of the result, and a block of code that executes when the expression is true or non-zero. The syntax for the IF statement is as follows:

If Expression:expr_true_suite

The Expr_true_suite code block of the IF statement executes only if the Boolean value of the result of the conditional expression is true, or the statement immediately following the block of code will continue to execute.
(1) Multi-conditional expressions
A single If statement can achieve multiple judgment conditions or negative judging conditions by using Boolean operators and, or, and not.
(2) block of code for a single statement
If the block of code for a compound statement (such as an IF clause, while, or for loop) contains only one line of code, it can be written on the same line as the preceding statement. such as if Make_hard_copy:send_data_to_printer (), such a single statement is legal, although it may be convenient, but this makes the code more difficult to read, it is recommended to move this line of code to the next line and properly indented. Another reason is that if you need to add new code, you still have to move it to the next line.
2. Else statement
Python provides an else statement that is used with the IF statement, and the program executes the code after the Else statement if the result of the conditional expression of the IF statement is false. Its syntax is as follows:

If Expression:expr_true_suiteelse:expr_false_suite

In the C language, the Else statement is not found outside the scope of the conditional statement, but unlike Python, the Else statement can be used in the while and for loops, and when used in a loop, the ELSE clause executes only after the loop completes, meaning that the break statement also skips the else block.
Example: showing the maximum number of digits from 10 to 20

View code slices to my Code slice

#!/usr/bin/env python    def showmaxfactor (num):   count = num/2 while   count > 1:    if (num% count = = 0): 
  print ' largest factor of%d '%d '% (num, count)    break    count = count-1   else:   print eachnum, ' is prim E ' for    Eachnum in range (10, 21):   

View code slices to my Code slice

Largest factor of 5 is  prime  largest factor of 6 are the  prime  largest factor of is 7< C15/>largest factor of 5  largest factor of are 8 is  prime  largest factor of 9 are  p Rime  

3. elif (i.e. else-if) statement
Elif is a Python else-if statement that checks if multiple expressions are true and executes code in a particular block of code when it is true. Like else, the Elif declaration is optional, but the difference is that there can be at most one else statement after the IF statement, but there may be 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 the Switch/case statement, but it can be emulated with other python constructs. In Python, a large number of IF-ELIF statements are not difficult to read.
View code slices to my Code slice

if User.cmd = = ' Create ':   action = "Create Item"  elif user.cmd = = ' Delete ':   action = ' Delete item '  elif use R.cmd = = ' Update ':   action = ' Update item '  else:   

The above statement can also be simplified with sequence and member relationship operators:

View code slices to my Code slice

If User.cmd in (' Create ', ' delete ', ' Update '):   action = '%s item '% User.cmd  else:   

You can also use a Python dictionary to give a more elegant solution, one of the biggest benefits of using a mapped object (such as a dictionary) is that its search operation is much faster than a sequence query such as a statement or a for loop.

View code slices to my Code slice

msgs = {' Create ': ' Create item ',    ' delete ': ' Delete item ',    ' update ': ' Update item '    }  default = ' Invalid ch ' Oice. Try Again! '  

4. Conditional expression (i.e. "ternary operator")
The ternary operator syntax is: X if C else Y, which requires only one line to complete the conditional Judgment and assignment:

View code slices to my Code slice

>>> x, y = 4, 3  >>> smaller = x if x < y else y  >>> smaller  

5. While statement
While is a conditional loop statement, a corresponding block of code is executed once if the condition after if is true, compared to the if declaration. The code block in the while is looped until the loop condition is no longer true.
(1) General syntax
The syntax for the while loop is as follows:

While Expression:suite_to_repeat

The suite_to_repeat clause of the while loop is executed all the time until the expression value is a Boolean false.
(2) Counting cycle

Count = 0while (Count < 9): print ' The index is: ', count count + = 1

The code block contains print and self-increment statements, which are executed repeatedly until count is no longer less than 9. The index count is printed at each iteration and then increased by 1.
(3) Infinite loop

While true:handle, indata = Wait_for_client_connect () Outdata = Process_request (indata) ack_result_to_client (handle, Outdata)

The infinite loop never ends, but it is not necessarily a bad thing, and many of the client/server systems of a communications Server work through it.
6. For statement
Another loop mechanism provided by Python is the For statement, which is the most powerful looping structure in Python. It can traverse a sequence member, which can be used in list parsing and generator expressions, which automatically invokes the next () method of the iterator, captures the stopiteration exception, and ends the loop (all of which happens internally). Python's for is more like a foreach loop in the shell or scripting language.

(1) General syntax
The For loop accesses all elements in an iterative object, such as a sequence or iterator, and ends the loop after all entries have been processed. Its syntax is as follows:
For Iter_var in iterable:
Suite_to_repeat
For Each loop, the Iter_var iteration variable is set to iterate over the current element of an object (sequence, iterator, or other object that supports iterations), which is provided to the SUITE_TO_REPEAT statement block for use.
(2) for sequence type
A For loop can iterate over different sequence objects, such as strings, lists, and tuples.
There are three basic methods of iterating the sequence:
Iterating through sequence items
View code slices to my Code slice

>>> namelist = [' Walter ', ' Nicole ', ' Steven ', ' Henry ']  >>> for eachname in NameList:  ...  Print Eachname, "Lim" ...  Walter Lim  Nicole Lim  Steven Lim  

Iterate a list: Each iteration, the Eacgname variable is set to a specific element in the list.
Iterating through the sequence index
View code slices to my Code slice

>>> namelist = [' Cathy ', ' Terry ', ' Joe ', ' Heather ', ' Lucy ']  >>> for Nameindex in range (Len (namelist )):  ...  Print "Liu,", Namelist[nameindex] ...  Liu, Cathy  Liu, Terry  Liu, Joe  Liu, Heather  

There is no iterative element, but rather iteration through the index of the list. But the direct iteration sequence is faster than the index iteration.
Using Item and Index iterations
View code slices to my Code slice

>>> namelist = [' Donn ', ' Shirley ', ' Ben ', ' Janice ', ' David ', ' Yen ', ' Wendy ']  >>> for me, Eachlee in EN Umerate (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  

(3) for iterator type
With a For loop access to the iterator and the method of accessing the sequence, the iterator does not represent a collection of circular 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 throws a stopiteration exception telling the program that the loop ends and the for statement internally calls next () and catches the exception.
The code for A for loop using an iterator is almost identical to using a sequence entry. In fact, in most cases, it is impossible to tell whether an iteration is a sequence or an iterator, so traversing an iterator may actually mean traversing a sequence, an iterator, or an object that supports iterations (it has the next () method).
(4) range () built-in function
The built-in function range () can turn a foreach-like for loop into a more familiar statement.
Python provides two different ways to call range (), and the full syntax requires two or three integer arguments: Range (start, end, step =1), range () returns a list containing all k, where start <= K < end , from start to end, K each increment ste,step cannot be zero, or an error occurs.
View code slices to my Code slice

>>> Range (3, 7)  [3, 4, 5, 6]  >>> for Eachval in range (2,, 3):  ...  Print "value is:", eachval ...  Value Is:2  value is:5  value is:8  value is:11  value is:14  

Range () also has two abbreviated syntax formats: Range (end) and range (start, end). Start defaults to 0 and step defaults to 1.
(5) Xrange () built-in function
Xrange () is similar to range (), but when there is a large list of scopes, xrange () may be more appropriate because it does not create a full copy of the list in memory. It is only used in the For loop, and it doesn't make sense to use it outside of the for loop. Its performance is much higher than the range () because it does not generate the entire list. In future versions of Python, range () may return an iterative object (not a list or an iterator) like xrange ().

(6) Built-in functions related to sequences
Sequence-dependent functions: sorted (), reversed (), enumerate (), and zip (), called sequence correlation, because two of the functions (sorted () and zip ()) return a sequence (list), while the other two functions (reversed () and Enumerate ()) returns an iterator (similar to a sequence).
7. Break and Continue statements
The break statement in Python can end the current loop and then jump to the next statement, similar to break in C. Often when an external condition is triggered (typically checked by an if statement), it needs to be exited immediately from the loop: The break statement can be used in the while and for loops.
The continue statement in Python is no different from the traditional continue in other high-level languages, and it can be used in the while and for loops. While loop is a condition
The For loop is iterative, so continue has to meet some prerequisites before starting the next loop, otherwise the loop ends normally.
When a continue statement is encountered in the program, 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 validate the conditional expression. If it is an iterative loop, it verifies that there are elements that can be iterated. The next iteration is only started if the validation succeeds.
View code slices to my Code slice

#!/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 INP  UT = = eachpasswd:     valid = True break     if not    valid: # (or valid = = 0)     print "Invalid input"     count-= 1     continue    else:      

A while, for, if, break, and continue are used together to validate user input. The user has three chances to enter the correct password to prevent the user from guessing the password.

8. Pass Statement
There is no corresponding empty curly brace or semicolon (;) in Python. To represent "do nothing" in C, the interpreter prompts for a syntax error if it does not write any statements where the child statement block is needed. As a result, Python provides a pass statement, which does nothing, i.e. NOP (no operation), and pass can also be used as a small technique in development to mark the code that will be completed later.

Def foo_func ():
Pass

This kind of code structure is useful for development and debugging, because it is possible to write code in order to set the structure down, but do not want it to interfere with other completed code, where it does not need to do anything place a pass, will be a good idea. In addition, it is often used in exception handling, such as when you track a non-fatal error and do not want to take any action.
9, Iterators and ITER () functions

(1) What is an iterator

The

iterator provides the class sequence object with an interface to a class sequence that can be used to iterate through the last entry of the sequence starting at 0, and iterating through the sequence using the "Count" method is simple. Python's iterations seamlessly support sequence objects, and it also allows programmers to iterate over non-sequential types, including user-defined objects. The
iterator is handy for iterating over objects that are not sequences but exhibit sequence behavior, such as a dictionary key, a file row, and so on. When iterating over an object entry using a loop, you do not have to focus on whether it is an iterator or a sequence.
(2) Why the iterator
iterator is defined: Provides an extensible iterator interface, performance enhancements to the list iteration, performance improvements in the dictionary iterations, and a real iterative interface, rather than the original random object access, You can create more concise and readable code when you are backward-compatible with all existing user-defined classes and extended simulated sequences and mapped objects, iterating over non-sequential collections, such as mappings and files.
(3) How to iterate
an iterator that has an object of the next () method, rather than counting by index. When a loop mechanism, such as a for statement, requires the next item, the next () method that invokes the iterator can obtain it. When the entry is all taken out, a Stopiteration exception is thrown, which does not mean that the error occurred, only that the external caller is done iterating.
However, iterators have some limitations. For example, you cannot move backwards, you cannot go back to the beginning, and you cannot copy an iterator. If you want to iterate over 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 iterators. The
reversed () built-in function returns an iterator that is accessed in reverse order. The enumerate () built-in function also returns an iterator. Another two new built-in functions: any () and all (), if the values of one or all of the entries in the iterator are Boolean true, their return value is true.
(4) using an iterator
sequence
Viewing code slices on codes derivation to my Code slice

>>> mytuple = (123, ' xyz ', 45.67)  >>> i = iter (mytuple)  >>> i.next ()  123  >>> i.next ()  ' xyz '  >>> i.next ()  45.670000000000002  >>> i.next ()  Traceback (most recent):   File "
 
  
   
  ", line 1, in 
  
   
    
     stopiteration 
  
    c17/>
  

In the For loop, for I in seq:do_something_to (i), it automatically calls the next () method of the iterator and monitors the stopiteration exception. The
Dictionary
Dictionaries and files are two other Python data types that can be iterated. The dictionary iterator iterates through its keys (keys), and the statement for Eachkey in Mydict.keys () can be abbreviated to for Eachkey in Mydict.
Python has also introduced three new built-in dictionary methods to define iterations: Mydict.iterkeys () (via the keys Iteration), Mydict.itervalues () (via values iteration), and Mydicit.iteritems () (Iterate by Key/value pairs). Note: The in operator can also be used to check if the dictionary key exists, and the Boolean expression Mydict.has_key (AnyKey) can be abbreviated to AnyKey in Mydict. The iterator generated by the
file
file object automatically calls the ReadLine () method. This allows the loop to access all lines of the text file. You can replace the for Eachline in Myfile.readlines () with a simpler for-eachline in MyFile.
(5) mutable objects and iterators
It is not a good idea to modify them when iterating over mutable objects, which is a problem before iterators occur. A sequence iterator simply records the current arrival of the element, so if the element is changed at iteration, the update is immediately reflected on the item you are iterating over. It is absolutely impossible to change this dictionary when iterating the key of the dictionary. It is possible to use the keys () method of the dictionary, because keys () returns a dictionary-independent list, and the iterator is bound to the actual object, and it will not continue to execute.
(6) How to create an iterator
calls ITER () on an object to get its iterator, which has the following syntax: ITER (obj) or ITER (func, Sentinel). If you pass a parameter to ITER (), it will check if you are passing a sequence, and if it is, it will iterate from 0 to the end of the sequence according to the index. Another way to create iterators is to use classes, and a class that implements the __iter__ () and Next () methods can be used as iterators. If you are passing two parameters to ITER (), it will call Func repeatedly until the next value of the iterator equals Sentinel.

10. List parsing
List parsing (lists comprehensions or indented 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 lists.
Python supports functional programming features such as Lambda, Map (), and filter (), which can be simplified as a list-parsing formula. Map () applies an action to all list members, filter () filters list members based on a conditional expression, and lambda () allows you to quickly create a single line of function objects.
Syntax for list parsing: [Expr for Iter_var in iterable], which iterates through all entries of the Iterable object. Where expr is applied to each member of the sequence, the final result value is the list that the expression produces, and the iteration variable does not need to be part of an expression.
View code slices to my Code slice

>>> [x * * 2 for X in range (6)]  

List-resolved expressions can replace built-in map () functions and lambda, and are more efficient. In conjunction with the IF statement, List parsing also provides an extended version of the syntax: [Expr for Iter_var in iterable if COND_EXPR], which filters/captures the sequence members that satisfy the conditional expression cond_expr at iteration.
Select the odd number in the sequence:
View code slices to my Code slice

>>> seq = [One, ten, 9, 9, ten, 9, 8,, 9, 7,, one, one]  >>> filter (lambda x:x% 2, seq) 
  [11, 9, 9, 9, 23°c, 9, 7, each]  >>> [x for x in seq if x% 2]  

Even without filter () and lambda, you can use list parsing to complete the operation and get the number you want.
Matrix Sample: Iterate over a matrix with three rows and five columns [(x+1,y+1) for x in range (3) for Y in range (5)].
Disk File Sample: If you have a data file text.txt, you need to calculate the number of all non-whitespace characters, you can split each line (split) into a word, 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 file size: >>>import os;os.stat (' Text.txt '). St_size. Add up the length of each word: >>>f.seek (0); sum ([Len (word) for line in F for word in line.split ()]).
11. Generator expression

A builder expression is an extension of list resolution that allows you to create a list of specific content in just one line of code. Another important feature is the generator, which is a specific function that allows you to return a value and then "pause" the execution of the code and restore it later.
One disadvantage of list parsing is the need to generate all the data to create the entire list. This can have a negative effect on iterators with a large amount of data, and the generator expression solves this problem by combining list parsing and generators.
Generator expressions are very similar to list parsing, and their basic syntax is basically the same. However, it does not really create a list of numbers but instead returns a generator that "yields" the entry after each calculation of an entry. The generator expression uses lazy evaluation, so it is more efficient in using memory. The generator does not let the list parse obsolete, it is just a memory using a more friendly structure, based on which there are many use generator places.
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 Sample: The above calculated text file in the sum of non-whitespace characters, if the size of the file becomes very large, then the memory performance of this line of code is very low, because to create a long list to hold the length of the word. To avoid creating a large list, use the generator expression to complete the sum operation, and the optimized code:>>> sum (len (word) for lines in the data for Word in Line.split ()), is to remove the square brackets, less two bytes, and more memory savings.
Cross-pairing example: The builder expression is like lazy list parsing (which is the main advantage of it), and 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 a sample to find the longest line in a file:
Previous methods:

View code slices to my Code slice

#!/usr/bin/env python    def Fun ():   f = open ('/ETC/MOTD ', ' R ')   longest = 0   alllines = [X.strip () for x in F.R Eadlines ()] #or alllinelens = [Len (X.strip ()) for X "F]   F.close () for line in   alllines:    linelen = Len (line) C7/>if linelen > Longest:   #or longest = max (alllinelens)     longest = Linelen   

The new method:

Replace the list resolution and Max () functions with the generator expression and remove the file open 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 iterators, and the contents of list parsing and generating expressions can be analyzed with examples.
(2) If there is insufficient, please leave a message, thank you first!

  • 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.