Basic Python Tutorial "reading notes"-2016/7/7

Source: Internet
Author: User

Hope to continue to update through the blog park, share and record the basic knowledge of Python to the advanced application of the dots drop!

Third Wave: 5th Chapter

[Overview] conditions, loops, and other statements

  In-depth introduction to conditional and circular statements, you'll see how the list derivation plays the role of loops and conditional statements, and finally introduces the use of Pass, Del, and EXEC statements.

[5.1] Print and import for more information

  First look at some of the better features of print and import.

For multiple applications, it is more appropriate to use the logging module log than the print statement.

[5.1.1] using a comma output

  It's also possible to print multiple expressions, just by separating them with commas.

Print greeting+ ', ', salutation,name

[5.1.2] To import something as another thing

When importing functions from a module, you can use the

Import Somemodule

From Somemodule import somefunction

From Somemodule import somefunction,anotherfunction,yetanotherfunction

From somemodule Import *

From Somemodule import somefunction as Othername

You can add an as clause at the end of the statement, or provide an alias for the entire module, or you can provide an alias for the function.

[5.2] Assignment Magic

Some special tricks for assignment statements.

[5.2.1] Sequence unpacking

Multiple assignment operations can be performed simultaneously:

x,y,z=1,2,3

X,y=y,x

Called a sequence unpacking or an iterative solution---to untie multiple worthwhile sequences and then place them in a sequence of variables. This feature is especially useful when a function or method returns a tuple (or other sequence or iterator object).

Assuming that you need to get (and delete) any key-value pairs in the dictionary, you can use the Popitem method, which returns the key-value as a tuple, which can be directly assigned to two variables:

scoundrel={' name ': ' Robin ', ' girlfriend ': ' Marion '}

Key,value=scoundrel.popitem ()

The number of elements in the unpacked sequence must be exactly the same as the number of variables placed on the left of the assignment symbol =.

[5.2.2] Chained assignment

Chained assignment is a shortcut to assigning the same value to multiple variables.

[5.2.3] Incremental Assignment

Incremental assignment, for standard operators such as *,/, and%. Incremental assignment can make your code more compact and concise, and in many cases easier to read.

[5.3] Statement block: The fun of indentation

  A statement block is a set of statements that executes or executes multiple times when the condition is true. You can create a statement block by placing a space in front of the code to indent the statement. You can also indent a statement block by using the tab character, revealing the move to the next tab character position, and a tab character position of 8 spaces. Each row in the block should be indented in the same amount. The colon is used to identify the beginning of a statement block, which indicates that the current block has ended when it is rolled back to the same indent as the closed block.

[5.4] Conditional and conditional statements

  Describes a method that lets a program choose whether to execute a block of statements.

[5.4.1] This is the role of Boolean variables

True value, also called a Boolean.

False, None, 0, "", (), [], {} will be interpreted as false false by the interpreter. Everything else has been interpreted as true.

Boolean values True and False are Boolean types, and BOOL functions can be used to convert other values.

[5.4.2] Conditional execution and if statement

The IF statement can implement conditional execution, and if the condition is determined to be true, execute the following block of statements. The condition is false and does not execute.

[5.4.3] Else clause

The clause is called because it is not a separate statement, but only as part of an if statement.

[5.4.4] elif clause

If you need to check multiple conditions, you can use Elif.

[5.4.5] Nested code block

If statements can be nested using the IF statement.

[5.4.6] more complex conditions

1. Comparison operators

X==y

X<y

X>y

X>=y

X<=y

X!=y

X is y x and Y are the same object

X is not y x and Y are different objects

X in Y X is a member of the Y container

x not in Y X is not a member of the Y container

In Python, the comparison and assignment operations can be connected, and several operators can be used together, such as: 0<age<100

2. Equality operators

If you want to know whether two things are equal, you should use the equality operator, which is two equals = =. A single equality operator is an assignment operator, which is used to change the value and cannot be compared.

3, is: identity operator

The IS operator determines identity rather than equality. The variables x and Y are bound to the same list, and the variable z is bound to another list with the same values and order. Their values may be equal, but they are not the same object.

To sum up: use the = = operator to determine whether two objects are equal, using is to determine whether the two are equal (the same object).

4, in: Membership operator

5. String and Sequence comparisons

Strings can be compared in alphabetical order.

The characters are arranged in their own order, and the order of the letters can be viewed with the Ord function, and the Ord function is opposite to the CHR function function. If you want to ignore the difference between uppercase and lowercase letters, you can use the string method upper and lower.

6. Boolean operators

And, or, not.

Short-circuit Logic and conditional expressions:

The Boolean operator has an interesting feature: it is evaluated only if a value is required. For example, an expression x and Y requires two variables to be true, so if X is false, the expression returns false immediately, regardless of the value of Y. This behavior is known as short-circuit logic short-circuit logic or lazy evaluation. means that all code after the Boolean operator is not executed. It is primarily to avoid executing code without using it.

A If B else c

If B is true, return a. Otherwise, return C. Note that this operator does not have to be hidden from temporary variables and can be used directly.

[5.4.7] Assertion

An Assert statement is useful if you need to make sure that a condition in the program must be true for the program to work, and it can place checkpoints in the program.

Assert 0<age<100, ' The Must be realistic! '

[5.5] Cycle

[5.5.1] While loop

While not name or Name.isspace ():

print ' Hello,%s! '% name

[5.5.2] For loop

An iterative object is an object that can be iterated in a sequential order.

The range function works like a Shard, which contains a lower bound, but does not contain an upper bound. If you want a lower limit of 0, you can provide only the upper limit.

If a For loop is available, try not to use the while loop.

The loop behavior of the Xrange function is similar to the range function, where the entire sequence is created one time with the range function, and xrange only one number at a time. Xrange is more efficient when it is necessary to iterate over a large sequence.

[5.5.3] Looping through a dictionary element

The keys method to get the key, if you only need the value, you can use d.values instead of D.keys. The D.items method returns a key-value pair as a tuple.

The order of the dictionary elements is usually meaningless. When iterating, the keys and values in the dictionary are guaranteed to be processed, but the processing order is indeterminate. If the order is important, you can save the key values in a separate list, such as sorting before the iteration.

[5.5.4] Some iterative tools

Some functions are useful when iterating through a sequence in Python. Some functions are in the Itertools module, and some Python built-in functions are also useful.

1. Parallel iterations

A program can iterate over two sequences at the same time.

names=[' Anne ', ' Beth ', ' George ', ' Damon '

AGES=[12,34,32,102]

For I in range (len (names)):

Print Names[i], "is", age[i], ' year old! '

The built-in zip function can be used for parallel iterations, which can "compress" two sequences together and return a list of tuples.

Zip (names,ages)

[(' Anne ', '), (' Beth ', '), (' George ', ' + '), (' Damon ', 102)]

For name,age in Zip (names,ages):

Print name, ' is ', age, ' years old! '

The ZIP function can also be used for any number of sequences. It is important to note that the zip can cope with unequal sequences and will stop when the shortest sequence is "exhausted".

Zip (range (5), xrange (1000000))

In the above code, it is not recommended to replace xrange with range---although only the first 5 digits are required, range calculates all the numbers, which can take a long time. Using xrange does not have this problem, it only calculates the first 5 digits.

2. Numbering iterations

To iterate over an object in a sequence, and also to get the index of the current object. You can use the built-in enumerate function:

For index,string in Enumerate (strings):

If ' xxx ' in string:

Strings[index]= ' [censored] '

3. Flipping and sorting iterations

Reversed and sorted: they are similar to the reverse and sort methods of the list, but work on any sequence or iterator object, instead of modifying the object in situ, instead returning the flipped or sorted version.

Large can be used in the For loop as well as in the Join method without any problems. However, you cannot use indexes, shards, and call the list method directly on it. If you want to do this, you can use the list type to convert the returned object.

[5.5.5] jump out of the loop

1. Break

2. Continue

Skips the remaining loop body, but does not end the loop.

3. While True/break idioms

While True:

Word=raw_input (' Please enter a word: ')

If not word:break

print ' The word was ' +word

The part of while true implements a loop that never stops itself. However, if a condition is added to the inside of the loop, the break statement is called when the condition is satisfied. This makes it possible to terminate the loop anywhere inside the loop rather than just at the beginning. The If/break statement naturally divides the loop into two parts: the 1th part is responsible for the initialization, and the 2nd part uses the 1th part to initialize the good data when the loop condition is true.

else clause in [5.5.6] loop

From math import sqrt

For n in range (99,81,-1)

Root=sqet (N)

If Root==int (root):

Print n

Break

Else

print "didn ' t find it!"

[5.6] List derivation---lightweight loops

  List comprehension is a way to create a new list using other lists. Use ordinary parentheses instead of square brackets to get a "tuple derivation".

[5.7] Threesome

  Three additional statements: Pass, Del, and exec.

[5.7.1] nothing happened.

Sometimes the program doesn't have to do anything. Pass statement. It can be used as a placeholder in your code. For example, the program requires an if statement and then tests, but lacks the code for one of the statement blocks. Because the empty block of code in Python is illegal, the workaround is to add a pass statement to the statement block.

[5.7.2] Using del Delete

In general, Python removes objects that are no longer used, because the consumer no longer references them through any variables or data structures.

When the variable is set to None, the dictionary "floats" in memory, and no name is bound to it. There is no way to get and use it, so the Python interpreter deletes the dictionary directly, and this behavior is called garbage collection.

Another way is to use the DEL statement. Not only does it remove a reference to an object, it also removes the name itself.

When both X and Y point to the same list:

x=[' Hello ', ' world '

Y=x

y[1]= ' python '

X

[' Hello ', ' python ']

Some people think that after deleting x, y disappears, but not:

del X

Y

[' Hello ', ' python ']

Why is that? Both X and Y point to the same list. But deleting x does not affect Y. The reason is that only the name is deleted, not the list itself. In fact, there is no way to delete the value in Python (nor do you need to think too much about deleting the problem, because the Python interpreter is responsible for the recycling of the memory when some of the values are no longer being used).

[5.7.3] using exec and eval to execute and evaluate strings

Sometimes it is necessary to dynamically create Python code and then execute it as a statement or evaluate it as an expression. However, this can be a serious potential security vulnerability, and the program may lose control of code execution if the program executes a subset of the string from a user-supplied piece of content as code.

1. exec

The statement that executes a string is exec.

Exec "print ' hello,world! '"

The concept of namespaces, or the role of scope, is a very important knowledge. You can now think of it as a place to save variables, similar to an invisible dictionary. So when a program executes an assignment such as x=1, the key x and value 1 are placed in the current namespace, which is generally the global namespace, but this is not required.

2. Eval

Eval is a built-in function similar to exec for "evaluation". The EXEC statement executes a series of Python statements, and eval evaluates the Python expression and returns the result value.

[5.8] Summary

printing:The print statement can be used to print multiple values separated by commas. If the statement ends with a comma, the following print statement continues to print on the same line

Import: You can use the import as statement to perform a local rename of a function.

assignment: through the sequence unpacking and chaining assignment function, multiple variable assignment can be assigned at once, and the variable can be changed in situ by increment assignment.

blocks: blocks are a way of grouping statements by indenting them.

condition: A conditional statement can execute on a condition or not execute a block of statements. If/elif/else. This topic is also called conditional expressions, such as: a If B else c

Assertion: The assertion is simply that it is certain that something is true. If an expression is false, the assertion causes the program to crash.

loops: You can use the Continue statement to skip the other statements in the block and continue the next iteration, or use the break statement to jump out of the loop.

List derivation: is an expression that looks like a loop, with a list derivation that creates a new list from the old list, applies a function to the element, filters out unwanted elements, and so on.

  Pass, Del, exec, eval:The pass statement does nothing and can be used as a placeholder. The DEL statement is used to delete a variable, or part of a data structure, but cannot be used to delete a value. The EXEC statement executes the string in the same way that the Python program executes. The Eval function evaluates an expression that is written in a string and returns the result.

[5.8.1] Useful functions

Chr (n) does not return a string containing one character (0≤n<256) represented by N when the ordinal n is passed in.

Enumerate (SEQ) produces the (index, value) pair for the iteration

Ord (c) returns the int value of a single character string

Range ([START,],STOP[,SETP])

Xrange ([START,],STOP[,SETP]) creates xrange objects for iteration

Zip (seq1,seq2,...) Create a new sequence for parallel iterations

Reversed (seq) produces a SEQ in the reverse version, used for iteration

Sorted (Seq[,cmp][,key][,reverse]) returns a list of sorted values in SEQ

            

Basic Python Tutorial "reading notes"-2016/7/7

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.