First, Introduction
Python's conditions and looping statements determine the program's control flow and reflect 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 true and false of the result, and a block of code that executes when the expression is true or not zero. The syntax for the IF statement is as follows:
If expression:
expr_true_suite
The Expr_true_suite code block of an IF statement executes only if the Boolean value of the result of the conditional expression is true, or the statement immediately following the code block is executed.
(1) Multi-condition expression
A single if statement can use Boolean operators and, or, and not to achieve multiple judgment conditions or negative judgment conditions.
(2) A block of code for a single statement
If a compound statement (such as an IF clause, a while, or a For loop) contains only one line of code, it can be written on the same line as the preceding statement. If Make_hard_copy:send_data_to_printer (), such a single-line statement is legitimate, although it may be convenient, but this makes the code more difficult to read, so it is recommended to move this line of code to the next line and reasonably indent. 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 an if statement, and if the result of a conditional expression of an If statement is false, the program executes the code after the Else statement. The syntax is as follows:
If expression:
expr_true_suite
Else:
expr_false_suite
In C, the Else statement is not found outside the scope of the conditional statement, but unlike Python, you can use the Else statement 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: Displays the maximum divisor of a number from 10 to 20
View a code slice from my Code chip
#!/usr/bin/env python
def showmaxfactor (num):
count = num/2 while
count > 1:
if (num count = = 0):
print ' largest factor of%d of%d '% (num, count)
break
count = count-1
else:
print eachnum, ' is prim E '
for Eachnum in range:
showmaxfactor (Eachnum)
View a code slice from my Code chip
Largest factor the 5 is
prime
largest factor of 6 are prime largest factor an is
7< C18/>largest factor of 5 largest factor an is 8 ' is prime largest factor ' is 9 ' is
p Rime
largest factor of 10
3, elif (ie 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. As with else, the Elif declaration is optional, but unlike the IF statement, there can be at most one else statement, but there may be any number of elif statements.
If expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
...
Elif expressionn:
exprn_true_suite
Else:
none_of_the_above_suite
In the future, Python may support switch/case statements, but it can be emulated with other python constructs. In Python, a large number of IF-ELIF statements are not difficult to read.
View a code slice from my Code chip
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 with sequence and member-relational operators:
View a code slice from my Code chip
If User.cmd in (' Create ', ' delete ', ' Update '):
action = '%s item '% user.cmd
else:
action = ' Invalid choice ... try Again! '
You can also use a Python dictionary to give a more elegant solution, and 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 like a statement or a for loop.
View a code slice from my Code chip
msgs = {' Create ': ' Create item ',
' delete ': ' Delete item ',
' update ': ' Update item '
}
default = ' Invalid ch Oice ... try Again! '
Action = Msgs.get (user.cmd, default)
4, conditional expression (that is, "ternary operator")
The ternary operator syntax is: X if C else Y, which requires only one line to complete the conditional judgment and assignment operation:
View a code slice from my Code chip
>>> x, y = 4, 3
>>> smaller = x if x < y else y
>>> smaller
3
5, while statement
while is a conditional loop statement, and if the condition after if is true, the corresponding code block is executed once. The code block in the while loop executes until the loop condition is no longer true.
(1) General grammar
The syntax for the while loop is as follows:
While expression:
suite_to_repeat
The suite_to_repeat clause of the while loop executes until the expression value is Boolean false.
(2) Counting cycle
Count = 0
while (Count < 9):
print ' The index is: ', count
count = 1
The code block contains print and self-add statements that are repeated until count is no longer less than 9. The index count is printed and then increased by 1 per iteration.
(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 communication server's client/server systems work through it.
6, for statement
another loop mechanism provided by Python is the For statement, which is the most powerful loop structure in Python. It can traverse a sequence member, can be used in list parsing and builder expressions, it automatically invokes the next () method of the iterator, captures the stopiteration exception, and ends the loop (all of which happen internally). The python for is more like a foreach loop in a shell or in a scripting language.
(1) General grammar
The For loop accesses all the elements in an iterated 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
Each loop, the Iter_var iteration variable is set to the current element of an iterative object (a sequence, iterator, or other object that supports iterations), and is provided to the SUITE_TO_REPEAT statement block for use.
(2) for sequence types
The For loop can iterate over different sequence objects, such as strings, lists, and tuples.
There are three basic methods of iterative sequences:
Iterating through sequence items
View a code slice from my Code chip
>>> namelist = [' Walter ', ' Nicole ', ' Steven ', ' Henry ']
>>> for eachname in NameList:
... Print Eachname, "Lim"
...
Walter Lim
Nicole Lim
Steven Lim
Henry Lim
Iterate over a list ... Each iteration, the Eacgname variable is set to a specific element in the list.
Iterating through a sequence index
View a code slice from my Code chip
>>> 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 iteration element, but an index iteration through the list. However, the direct iteration sequence is faster than the index iteration.
Using Items and index iterations
View a code slice from my Code chip
>>> namelist = [' Donn ', ' Shirley ', ' Ben ', ' Janice ', ' David ', ' yen ', ' Wendy '] &G
T;>> 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) for iterator type
With a for loop accessing the iterator and accessing the sequence, the iterator does not represent a collection of loop entries, and the iterator object has a next () method, which returns the next entry after the call. After all entries have been iterated, the iterator throws a stopiteration exception to tell the program loop to end, the for statement internally calls next () and catches the exception.
The code for A for loop using an iterator is almost exactly the same as 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 for loop like foreach into a more familiar statement.
Python provides two different ways to call range (), and the full syntax requires two or three integer parameters: Range (start, end, step =1), range () returns a list containing all k, where start <= K < end , from start to end, K increments every time ste,step can not be zero, otherwise an error will occur.
View a code slice from my Code chip
>>> 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 does not make sense to use it outside of the for loop. Its performance is far higher than range () because it does not generate an entire list. In a future version of Python, Range () may be like xrange (), returning an iterative object (not a list or an iterator).
(6) Built-in functions related to sequences
sequence-related functions: sorted (), reversed (), enumerate (), and zip (), called Sequence correlation "is because two functions (sorted () and zip ()) return a sequence (list), while the other two functions (reversed () and enumerate ()) return iterators (similar sequences).
7, break, and Continue statements
The break statement in Python can end the current loop and then jump to the next statement, like a break in C. Commonly used when an external condition is triggered (generally through an if statement), you need to exit immediately from the loop ... The break statement can be used in a while and a For loop. The continue statements in
python are no different from the traditional continue in other high-level languages, and can be used in while and for loops. While loops are conditional
, and for loops are iterations, continue must meet some prerequisites before starting the next loop, otherwise the loop will end normally.
Program When the continue statement is encountered, the program terminates the current loop, ignores the remaining statements, and then returns to the top of the loop. Before we begin 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 still elements that can be iterated. The next iteration is only initiated if the validation succeeds.
View the code on the codepage to derive from 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:
break
A while, a for, if, a break, and a continue are used in conjunction 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 brace or semicolon (;) in Python. To represent the words "do nothing" in C, and if you need a block of child statements without writing any statements, the interpreter prompts for a syntax error. As a result, Python provides a pass statement that does nothing, that is, NOP (no OPeration), and pass can also be used as a small technique in development to mark code that will be completed in the future.
Def foo_func ():
Pass
Such a code structure is useful for development and debugging, because it may be a good idea to write the code first, but you don't want it to interfere with other completed code, and place a pass without it doing anything. It is also used frequently 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
Iterators provide a class sequence object with an interface to a sequence of classes, and can use their index to "iterate" from 0 to the last entry in the sequence, and it is easy to iterate through the sequence with a "count" method. Python iterations seamlessly support sequence objects, and it also allows programmers to iterate over unordered types, including user-defined objects.
Iterators are handy for iterating over objects that are not sequential but exhibit sequence behavior, such as the key of a dictionary, the rows of a file, and so on. When using a loop to iterate over an object entry, you do not have to pay attention to whether it is an iterator or a sequence.
(2) Why to iterator
The definition of an iterator: provides an extensible iterator interface, brings performance enhancements to list iterations, performance promotion in dictionary iterations, and creation of true iterative interfaces, rather than original random object access, backward compatibility with all existing user-defined classes, and extended analog sequences and mapped objects. When iterating over a collection of sequences, such as mappings and files, you can create more concise, readable code.
(3) How to iterate
The iterator has an object for the next () method, rather than counting by index. When a looping mechanism (for example, a for statement) requires the next item, the next () method of the iterator is invoked to obtain it. When the entry is all removed, a Stopiteration exception is thrown, which does not mean that the error occurred, but simply tells the external caller that the iteration is complete.
However, iterators have some limitations. For example, you cannot move backwards, you cannot go back to the beginning, or 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 with an inverse sequence access. The enumerate () built-in function also returns an iterator. Another two new BUILTIN functions: any () and all (), if the value of one or all of the entries in the iterator is Boolean true, they return the value true.
(4) Using iterators
Sequence
View a code slice from my Code chip
>>> mytuple = (123, ' xyz ', 45.67)
>>> i = iter (mytuple)
>>> i.next ()
123
>>> i.next ()
' xyz '
>>> i.next ()
45.670000000000002
>>> i.next (
) Traceback (most recent):
File "<stdin>", line 1, in <module>
stopiteration
In the For-loop seq:do_something_to (i), it automatically invokes the next () method of the iterator and monitors the stopiteration exception.
Dictionary
Dictionaries and files are two other iterations of the Python data type. The dictionary iterator iterates through its keys (keys), and the statement for Eachkey in Mydict.keys () can be abbreviated to the 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 () (through values iterations), and Mydicit.iteritems () (Iterate through Key/value). Note: The in operator can also be used to check whether the key exists in the dictionary, and the Boolean expression Mydict.has_key (AnyKey) can be abbreviated to AnyKey in Mydict.
File
The ReadLine () method is automatically invoked by the iterator generated by the file object. This allows the loop to access all the lines of the text file. You can replace the for Eachline in Myfile.readlines () with a simpler for eachline in MyFile.
(5) Variable objects and iterators
It is not a good idea to modify them when iterating over mutable objects, which is a problem before the iterator emerges. The iterator of a sequence simply records the current arrival of the first few elements, so if the element is changed at the time of the iteration, the update is immediately reflected in the entry for your iteration. You cannot change this dictionary when iterating over the key of the dictionary. Using the dictionary's keys () method is possible because the keys () return a list that is independent of the dictionary, and the iterator is bound to the actual object, and it will not go on.
(6) How to create an iterator
Invoking ITER () on an object can get its iterator, and its syntax is as follows: ITER (obj) or ITER (func, Sentinel). If you pass a parameter to ITER (), it will check that you are passing a sequence, and if so, 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 pass two parameters to ITER (), it will repeatedly call Func until the next value of the iterator equals Sentinel.
10. List resolution
List Resolution (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 create lists dynamically.
The functional programming features supported by Python, such as the Lambda, map (), and filter (), can be simplified to a list parsing formula through list parsing. 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 function object with only one row.
List parsing syntax: [Expr for Iter_var in iterable], which iterates over all entries of the Iterable object. Expr is applied to each member of the sequence, and the final result value is the list produced by the expression, and the iteration variable does not need to be part of the expression.
View a code slice from my Code chip
>>> [x * * 2 for X in range (6)]
[0, 1, 4, 9, 16, 25]
List-parsed expressions can replace the built-in map () functions and lambda, and are more efficient. Combining 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 meet the conditional expression cond_expr during the iteration.
Pick out the odd number in a sequence:
View a code slice from my Code chip
>>> seq = [9, 9, 9, 8, 9, 7,, one, one]
>>> filter (lambda x:x% 2, seq)
[11, 9, 9, 9, 9, 7, one]
>>> [x for x in seq if x% 2]
[11, 9, 9, 9, 23, 9, 7, 11]
Even without the 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-white characters, you can split each line (split) for the word, and then calculate the number of words:>>> f = open (' Hhga.txt ', ' R '); Len ([ Word for line in F for word in line.split ()]. Calculate file size quickly: >>>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 containing specific content in just one line of code. Another important feature is the builder, which is a specific function that allows you to return a value and then "pause" the execution of the code and resume it later.
One disadvantage of list resolution is the need to generate all of the data to create the entire list. This may have a negative effect on an iterator with a large amount of data, and the builder expression solves the problem by combining the list resolution and the generator.
Builder expressions are very similar to list resolution, and their basic syntax is essentially the same. But instead of actually creating a list of numbers, it returns a generator that, after each calculation of an entry, "generates" (yield). The builder expression uses "deferred calculation" (lazy evaluation), so it is more efficient in using memory. The builder does not let the list resolve obsolete, it is just a more user-friendly structure for memory usage, and based on this, there are many uses for generator places.
List parsing Syntax:
[Expr for Iter_var in iterable if COND_EXPR]
Builder expression Syntax:
(Expr for Iter_var in iterable if cond_expr)
Disk File Sample: The sum of the non-white-space characters in the computed text file above, if the size of the file becomes large, the memory performance of this line of code is very low because you want to create a long list to hold the length of the word. To avoid creating a large list, using a builder expression to complete the summation operation, the optimized code:>>> sum (len (word) for lines in data for word in Line.split ()), is to remove the square brackets, less than two bytes, and more memory savings.
Cross-pairing example: The builder expression is like lazy list parsing (which is the main advantage), 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-cols ()).
To refactor the sample, look for an example of the longest row in the file:
Previous methods:
View a code slice from my Code chip
#!/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 in F]
F.close () to line in
alllines:
linelen = Len (line) C8/>if linelen > Longest: #or longest = max (alllinelens)
longest = Linelen return
longest
The New approach:
replaces list resolution and MAX () functions with builder expressions and removes file open mode (default is read): Return Max (Len (X.strip)) for X in Open ('/ETC/MOTD ')).
Three, summary
(1) Itertools modules are added to support the application of iterators, and the contents of list parsing and generation expressions can be combined with instance analysis.
(2) If there is a shortage, please leave a message, thank you first!