Brief introduction
Interested to see: Explanatory language + Dynamic type language + strongly typed language
Interactive mode: (mainly to test, you can try Ipython)
Copy CodeThe code is as follows:
$python
>>> print ' Hello World '
Script
Copy the Code code as follows:
#!/usr/bin/env python
print ' Hello World '
Environment:
Recommended python2.7 + Easy_install + pip + virtualenv + Ipython
Indent in
The Python function does not have a distinct begin and end, and does not indicate the opening and closing curly braces of the function. The only delimiter is a colon (:), and then the code itself is indented.
Example:
Copy the Code code as follows:
#函数
def func (value):
Print Value #缩进
if value = = 1:
Value + = 1
elif value = = 2:
Pass
Else
Value + = 10
Identifier
Variables are examples of identifiers. An identifier is a name used to identify something. When naming identifiers, you should follow these rules:
Identifiers in 1.python are case-sensitive.
2. Identifiers start with letters or underscores, and can include letters, underscores, and numbers, case sensitive
3. Identifiers beginning with the following underscore are of special significance.
A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class and cannot be imported with "from XXX import *";
A double underscore (__foo) represents a private member of a class;
A double underscore (foo) represents a special method-specific identifier for Python, such as Init (), which represents the constructor of a class.
4. Identifiers cannot be reserved words
Copy the Code code as follows:
and elif Global or yield
Assert else if pass
Break except import print
Class exec in Raise
Continue finally is return
def for Lambda try
Del from not while
Variable
Assignment statements
1, Assignment statement establish object reference value
2. The variable name will be set when the value is first assigned.
3. The variable name must be assigned before the reference, and cannot reference a variable with no value declared
How to assign a value
Simple assignment
Variable (variable) =value (value)
Copy the Code code as follows:
s = ' spam '
Multi-variable assignment
The original tuple and list assignment statements in Python are formed and finally generalized to accept that the right side can be any type of sequence, as long as the lengths are equal. Note that the length must be equal
Variable1,variable2,... =value1,value2,...
Copy the Code code as follows:
S,h = ' A ', ' B ' tuple assignment, positional ' common '
[S,h] =[' A ', ' B '] list assignment, positional
a,b,c,d = ' spam ' sequence assignment, versatility
a,*b = ' spam ' Extended sequence unpacking (Python3)
Multi-Objective assignment
Copy the Code code as follows:
A=b=variable
s = h = ' spam ' Multi-objective assignment
Note: Multiple variable memory refers to the same object, which is required for mutable types, and modifies one to affect other
Self-variable assignment
Copy the Code code as follows:
such as +=,-=,*= and so on.
In the custom assignment, Python computes only once, and the normal notation is calculated two times;
The custom assignment modifies the original object instead of creating a new object.
Copy the Code code as follows:
s +=42 Enhanced Assignment
x + = y
Advantages:
Copy the Code code as follows:
Only one calculation is needed on the left, and the optimization technology is modified automatically, faster
L +=[] in situ modification
L = l+[] Copy, generate new Object
Operator
An expression can be decomposed into operators and operands
The function of an operator is to accomplish something that is represented by a symbol such as + or another specific keyword
operator requires data to be manipulated, so that data is called the operand
Operator precedence list (from highest to lowest)
Copy the Code code as follows:
Operator description
' Expr ' string conversion
{key:expr,...} Dictionary
[Expr1,expr2 ...] List
(EXPR1,EXPR2,...) Meta-group
function (expr,...) call
X[index:index] Slices
X[index] Subscript index value
X.attribute Property Reference
~x bitwise inversion
+x,-x positive, negative
X**y Power
X*y,x/y,x%y multiply, divide, take modulo
X+y,x-y Plus, minus
x< >y shift
X&y Bitwise AND
X^y Bitwise XOR OR
X|y bitwise OR
X =y,x>y comparison
X is y,x are not y equals test
X in y,x not in Y member judgment
Not x Logic No
X and Y Logic and
x or y logic or
Lambda arg,...: expr Lambda anonymous function
Binding law
Operators are usually left-to-right, i.e. operators with the same precedence are evaluated in left-to-right order
Calculation Order
By default, the operator precedence table determines which operator is evaluated before another operator. However, if you want to change the order in which they are calculated, you have to use parentheses. Good practice: Default to complex operation parentheses, rather than relying on default binding and calculation Order
Truth
Truth test
1. Any non-0 numeric or non-empty objects are true
2, number zero, empty object and special object none are False
3. Comparisons and equivalence tests are recursively applied to data structures
4. Comparison and equality tests will return TRUE or False
Truth table
Copy the Code code as follows:
Object/Constant Value
"" False
"String" really
0 off
2>=1 really
-2<=-1 really
() empty element group false
[] Empty list fake
{} Empty dictionary false
None Fake
Boolean expression
Three types of Boolean expression operators
Copy the Code code as follows:
X and Y
X or Y
Not X
Comparison
Numbers are compared by relative size
strings are compared in dictionary order, one character by one character
List and tuples compare the contents of each section from left to right
The dictionary is compared by a sorted list of key values
Numeric mixed type comparisons are wrong in Python3, but python2.6 support, fixed but arbitrary collation
Boolean number
There are two values that never change true,false
Boolean is a subclass of an integral type, but cannot be re-inherited
The default value for an object without the nonzero () method is True
For any number or empty set with a value of 0, the value false
In mathematical operations, the true and false of the Bollean value correspond to 1 and 0 respectively.
Basic Control Flow
If
Basic conditional test statements to determine the different situations that may be encountered and to operate on different situations
Basic form
Copy the Code code as follows:
If <条件> :
<语句>
Elif <条件> :
<语句>
Else
<语句>
Attention
Python is judged by indentation, and the elif and else sections are optional
Example:
Copy the Code code as follows:
A = 1
b = 2
c = 3;d=4 #两个放一句用分号隔开, but recommended branch
If a < b and C < d:
Print ("Branch A")
Elif A = = B:
Print ("Branch B")
Else
Print ("Branch C")
Switch
Python itself does not have a switch statement and, if needed, does the same with If/elif/else, and in some cases it can be considered in a dictionary
can also be used in the form of dict
If/else ternary operator
Copy the Code code as follows:
A = ((X and Y) or Z)
A = Y if X else Z
Example: a = ' t ' if x else ' a '
[Code]
For
Basic syntax
Loop control statement that can be used to loop through a sequence
The else block is optional, executed at the end of the loop, if break terminates the loop, else does not execute
Format:
[Code]
For <对象变量> in <对象集合> :
If <条件> :
Break
If <条件> :
Continue
<其他语句>
Else
<其他语句>
Attention:
1. Object collections can be lists, dictionaries, tuples, etc.
2.for.. In loops are appropriate for any sequence
3.for traversing a dictionary, the key of the dictionary is traversed
Copy the Code code as follows:
Rang & Xrange
A list of integers can be produced by using the range () function to complete the counting cycle
Copy the Code code as follows:
Range ([Start,] stop[, step])
Start optional parameter, start number
Stop terminating number, if x, produces a list of integers from 0-(x-1)
Step optional parameter, step size, default 1 without write
Range (1,5) contains a sequence of [1,2,3,4]
Xrange and Range differences
(python3.x can be ignored.)
In the Range method, it generates a list of objects, but in xrange, it produces a Xrange object, and when the return is not very large, or in a loop, basically is the case from the beginning, the two methods are almost as efficient. However, when the return is very large, or the loop often will be break out, or recommend the use of xrange, which will save space, but also improve efficiency.
Copy the Code code as follows:
>>> Print Range (1, 5)
[1, 2, 3, 4]
>>> print xrange (1, 5)
Xrange (1, 5)
In the above statement, RANGE returns a normal list, and Xrange returns an object of a specific xrange type. Because the Xrange method also creates an integer list (which uses the same parameters), it is very similar to the Range method. However, the Xrange method creates an integer in the list only when it is needed. The Xrange method is more appropriate when you need to iterate over a large number of integers because it does not create a large list, which consumes a lot of computer memory.
While
Similar to the IF statement, contains a conditional test statement, which loops, allowing repeating execution of a block of statements.
Optional ELSE statement block, with the for else block.
Format:
Copy the Code code as follows:
While <条件> :
If <条件> :
Break
If <条件> :
Continue
<其他语句>
Else
<语句>
Description
The Else block is executed if the while loop condition becomes false
If a break is used to end a loop, the while optional else block does not execute
Python does not have a do or do Until loop statement
Break & Continue & Pass
Break, terminates the loop statement, stops the loop, and if it terminates in the For/while loop, the else does not execute
Continue, end current, go to the next cycle-jump to the beginning of the nearest loop (to the first line of the loop)
Pass doesn't do anything, it's just an empty placeholder statement, which is used in situations where the syntax must have a statement, but the program does nothing.
Loop Else BLOCK: Executes only if the loop is normally left, i.e.
If you terminate a break from a for or while loop, any corresponding loop else block will not execute. Remember that break statements can also be used in a for loop
Other
Tips for Writing loops:
It is unsafe to modify the iteration sequence during the iteration (only if a mutable sequence such as a linked list is used). If you want to modify the sequence of your iteration (for example, to copy a selection), you can iterate over its copy. It is easy to do this with the cut logo
>>> Copy the Code code as follows:
For x in a[:]: # Make a slice copy of the entire list
... if Len (x) > 6:a.insert (0, X)
When looping in a dictionary, the keywords and corresponding values can be read at the same time using the Iteritems () method.
Copy CodeThe code is as follows:
>>> Knights = {' Gallahad ': ' The Pure ', ' Robin ': ' The Brave '}
>>> for K, V in Knights.iteritems ():
.. print K, V
...
Gallahad the Pure
Robin the Brave
When looping through a sequence, the index position and corresponding value can be obtained at the same time using the enumerate () function.
Copy CodeThe code is as follows:
>>> for I, V in enumerate ([' Tic ', ' tac ', ' toe ']):
.... Print I, V