the characteristics of Python
1. Simple
Python is a language that represents simple ideas.
2. easy to learn
Python has an extremely simple syntax.
3. free, open source
Python is one of the floss (free/open source) software.
4. high-level language
Using Python to write a program eliminates the low-level details of how to manage the memory used by the program.
5. Portability
Python has been ported to a number of platforms, including Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, Aros, as/400,
BeOS, os/390, z/OS, Palm OS, QNX, VMS, Psion, Acom RISC os, VxWorks, PlayStation, Sharp Zaurus,
Windows CE even has pocketpc.
6. Interpretative
Can be run directly from the source code. Inside the computer, the Python interpreter converts the source code into the middle form of the bytecode and translates it into the machine language used by the computer.
7. Object-oriented
Python supports both process-oriented programming and object-oriented programming.
8. Scalability
Some programs can be written in other languages, such as C + +.
9. can be embedded type
Python can be embedded in a C + + program to provide scripting functionality.
a rich library
The Python standard library is really huge. It can help you with all sorts of work, including regular expressions, document generation, unit tests, threads, databases, Web browsers, CGI, FTP,
e-mail, XML, RPC, HTML, WAV files, password systems, GUI (graphical user interface), TK, and other system-related operations.
---------------Split Line------------------------The following is the basic syntax for Python---------------------------------------------------------
I. Basic Concepts
1. There are four types of Python: integers, long integers, floating-point numbers, and complex numbers. integers, such as 1 long integers are relatively large integer floating-point numbers such as 1.23, 3E-2 complex numbers such as 1 + 2j, 1.1 + 2.2j
2. String (sequence of characters) the use of single and double quotes in Python is exactly the same. Use triple quotes (' "or" ") to specify a multiple-line string. Escape character ' \ ' natural string, by adding R or R before the string. If the R "This is a lines with \ n" is displayed, it is not a newline. Python allows you to handle Unicode strings prefixed with u or u, such as u "This is a Unicode string". The string is immutable. cascading strings in literal terms, such as "This" ' is ' string ' is automatically converted to this is string.
3. The name of the first character must be a letter or underscore ' _ ' in the alphabet. The other parts of the identifier consist of letters, numbers, and underscores. Identifiers are sensitive to case sensitivity.
4. The Object
Any "thing" that is used in a Python program becomes an object.
5. Logical AND Physical lines
The physical line is what we see when we write the program, and the logical line is what Python sees.
A semicolon in Python; Identifies the end of a logical line, but in practice each physical row is written with only one logical line, and the semicolon can be avoided.
You can write a logical line in more than one physical row, as follows:
s = "Peter is \"
Writing this article "
The use of above is called ' Clear line connection ', another example:
Print \
"Peter"
6. Indent
Whitespace is very important in python, the white space at the beginning of the line is the most important, also known as indentation. White space (spaces and tabs) at the beginning of a line determines the indentation level of the logical row, which determines the statement
Group. This means that statements at the same level must have the same indentation, and each group of such statements is called a block.
Note: Do not mix spaces and tabs to indent because they do not work across different platforms.
ii. operators and Expressions
1. Operator and its usage
operator |
name |
Description |
Example |
+ |
Add |
Add two objects |
3 + 5 gets 8. ' A ' + ' B ' gets ' ab '. |
- |
Reducing |
Get negative numbers or a number minus another number |
-5.2 Gets a negative number. 50-24 get 26. |
* |
By |
Multiply two numbers or return a string that is repeated several times |
2 * 3 get 6. ' La ' * 3 gets ' Lalala '. |
** |
Power |
Returns the Y-power of X |
3 * * 4 gets 81 (ie 3 * 3 * 3 * 3) |
/ |
Except |
x divided by Y |
4/3 gets 1 (the integer division gets the integer result). 4.0/3 or 4/3.0 get 1.3333333333333333 |
// |
Take the Divide |
The integer part of the return quotient |
4//3.0 gets 1.0 |
% |
Take the mold |
Returns the remainder of a division |
8%3 got 2. -25.5%2.25 got 1.5. |
<< |
Move left |
Shifts a number of bits to the left a certain number (each number in memory is represented as a bit or binary number, i.e. 0 and 1) |
2 << 2 get 8. --2 is expressed as 10 by bit |
>> |
Move right |
Move a number of bits to the right by a certain number |
One >> 1 get 5. --11 is expressed as 1011 by bit, 1 bits to the right and 101, or 5 in decimal. |
& |
Bitwise AND |
The bitwise of number and |
5 & 3 Get 1. |
| |
by bit or |
Number of bitwise OR |
5 | 3 Get 7. |
^ |
Per-bitwise XOR OR |
The bitwise XOR of the number or |
5 ^ 3 Get 6 |
~ |
Flip by bit |
The bit flip of X is-(x+1) |
~5 got 6. |
< |
Less than |
Returns whether x is less than Y. All comparison operators return 1 to represent true, and 0 to represent false. This is equivalent to the special variable true and false respectively. Note that these variable names are capitalized. |
5 < 3 returns 0 (that is, false) and 3 < 5 returns 1 (that is, true). Comparisons can be any connection: 3 < 5 < 7 returns TRUE. |
> |
Greater than |
Returns whether x is greater than Y |
5 > 3 returns TRUE. If two operands are numbers, they are first converted to a common type. Otherwise, it always returns false. |
<= |
Less than or equal to |
Returns whether x is less than or equal to Y |
x = 3; y = 6; X <= y returns True. |
>= |
Greater than or equal to |
Returns whether x is greater than or equal to Y |
x = 4; y = 3; X >= y returns True. |
== |
Equals |
Compare objects for Equality |
x = 2; y = 2; x = = y returns True. x = ' str '; y = ' StR '; x = = y returns false. x = ' str '; y = ' str '; x = = y returns True. |
!= |
Not equal to |
Compare two objects for unequal |
x = 2; y = 3; X!= y returns True. |
Not |
Boolean "Non" |
Returns False if X is true. If x is False, it returns true. |
x = True; Not Y returns false. |
and |
Boolean "and" |
If x is False,x and Y returns false, it returns the calculated value of Y. |
x = False; y = True; X and Y, which returns false because X is false. Here, Python does not compute y because it knows that the value of the expression must be false (because X is false). This phenomenon is called short-circuit calculation. |
Or |
Boolean "or" |
If x is true, it returns true, otherwise it returns the calculated value of Y. |
x = True; y = False; X or Y returns true. Short-circuit calculations are also applicable here. |
2. Operator precedence (from low to high)
operator |
Description |
Lambda |
Lambda expression |
Or |
Boolean "or" |
and |
Boolean "and" |
Not X |
Boolean "Non" |
In,not in |
Member Test |
Is,is not |
Identity test |
<,<=,>,>=,!=,== |
Comparison |
| |
by bit or |
^ |
Per-bitwise XOR OR |
& |
Bitwise AND |
<<,>> |
Shift |
+,- |
Addition and subtraction |
*,/,% |
Multiplication, division and remainder |
+x,-x |
PLUS sign |
~x |
Flip by bit |
** |
Index |
X.attribute |
Attribute reference |
X[index] |
Subscript |
X[index:index] |
Addressing segments |
F (Arguments ...) |
Function call |
(Experession,...) |
Binding or tuple display |
[Expression,...] |
List display |
{Key:datum,...} |
Dictionary display |
' Expression,... ' |
String conversions |
3. Python console output using print
Print "abc" #打印abc并换行
print "abc%s"% "D" #打印abcd
print "abc%sef%s"% ("D", "G") #打印abcdefg
third, control flow
1. If statement
i = ten
n = Int (raw_input ("Enter a number:"))
if n = i:
print "equal"
elif N < i:
print "Lower" C13/>else:
print "Higher"
2. While statement
While True:
pass
else:
pass
#else语句可选, the Else statement is executed when the while is false. Pass is an empty statement.
3. For loop for ... in
For I in range (0, 5): print
i
else:
Pass
# printing 0 to 4
Note: Executes the ELSE statement when the For loop ends;
Range (A, B) returns a sequence, starting from A to B, but excluding b,range the default step is 1, you can specify a step, range (0,10,2);
4. Break Statement
Terminates the loop statement, and any else that corresponds to the loop is not executed if it is terminated from a for or a while.
5. Continue statement
The continue statement is used to tune the remaining statements of the current loop, and then proceed to the next round of loops.
Four, function
Functions are defined by def . The DEF keyword follows the identifier name of the function followed by a pair of parentheses, which can contain a variable name that ends with a colon, followed by a statement, which is the function body.
Def sumof (A, B): return
A + b
1. Function Parameters
The parameter name in the function is ' formal parameter ', and the value passed when calling the function is ' argument '
2. Local Variables
Variables defined within a function have nothing to do with other variables that have the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable.
Global statement that uses the global statement to assign a value to a variable outside of a function.
def func ():
Global x
print "x is", x
x = 1
x = 3
func ()
print x
#3
3. Default Parameters
Some parameters of the function can be ' optional ' by using the default parameters.
Def say (msg, times = 1):
print msg * times
Say ("Peter")
Say ("Peter", 3)
Note: Only those parameters at the end of the formal parameter list can have default parameter values, that is, you cannot declare a formal parameter with a default value before declaring a function parameter, and then declare a formal parameter that has no default value, only because the value assigned to the formal parameter is assigned based on the position.
4. Key Parameters
If a function has many parameters, and now only wants to specify a portion of it, you can assign values (called ' key parameters ') to these parameters by name.
Pros: Don't worry about the order of the parameters, make the function simpler, and assume that the other parameters have default values, and you can assign values to only those parameters that we want.
def func (A, b=2, c=3):
print ' A is%s ', B is%s, C is%s '% (a, B, c)
func (1) #a is 1, B are 2, C is 3
func (1, 5 ) #a is 1, B are 5, C is 3
func (1, C = ten) #a is 1, B is 2, C is ten
func (c =, a =) #a is, B are 2, C is 20
5. Return Statement
Returns statements are used to return from a function, that is, to jump out of a function. You can return a value from a function.
A return statement with no returned value is equivalent to returns None. None means a special type without anything.
6. Docstrings (document String)
def func (): "' This is self-defined function does nothing '" Pass
print func.__doc__
#This is self-defined function
#
#Do Nothing
Five, module
A module is a file that contains all of the functions and variables you define, and the module must have a. py extension. A module can ' enter ' (import) from another program to take advantage of its functionality.
Import other modules in a Python program using ' import ', the imported modules must be in the directory listed in Sys.path because the Sys.path first string is the current directory, so the module in the current directory can be imported into the program.
1. Byte-compiled. pyc File
The import module is time-consuming, and Python optimizes it so that the import module is faster. One way is to create byte-compiled files with the. PYc as the extension.
PYC is a binary file that is a compiled byte code for a py file and a cross-platform (platform-independent) bytecode that is executed by a Python virtual machine, similar to
The concept of Java or. NET virtual machines. The content of the PYC is related to the Python version, and the PYC files are different when compiled with different versions.
2. From. Import
If you want to use a variable or other module directly, without the ' module name +. ' Prefix, you can use the from. Import
For example, the Argv,from sys import argv or from sys import * that you want to directly use SYS
3. __name__ of Modules
Each module has a name, the py file corresponding module name defaults to the Py file name, can also be in the Py file for __name__ assignment; if it is __name__, the module is described by the user
Run separately.
4. Dir () function
DIR (SYS) returns a list of the names of the SYS modules, or DIR (), if no argument is supplied, and the list of defined names in the current module is returned.
Del-> Deletes a variable/name, after del, the variable can no longer be used.
Six, data structure
Python has three types of built-in data structures: lists, tuples, and dictionaries.
1. List
A list is a data structure that handles a set of ordered items, which are variable data structures. The items in the list are contained in square brackets [], eg: [1, 2, 3], empty list []. Determine if a list contains an item that can be used in, such as L = [1, 2, 3]; Print 1 in L; #True; supports indexing and slicing operations; If the index is out of range, Indexerror; use function len () to view the length; Use del to delete items from the list, Eg:del l[0] # If out of range, Indexerror
The list function is as follows:
Append (value) ---Add Item value to the end of the list
L = [1, 2, 2]
l.append (3) #[1, 2, 2, 3]
count (value) ---Returns the number of items in the list with values value
L = [1, 2, 2]
print L.count (2) # 2
Extend (LIST2) ---Add a list to the end of the list List2
L = [1, 2, 2]
L1 = [A]
l.extend (L1)
print L #[1, 2, 2, 10, 20]
Index (value, [Start, [stop]]) ---Returns the first value in the list that appears, if not, the exception valueerror
L = [1, 2, 2]
a = 4
try:
print L.index (a)
except ValueError, ve:
print "There are no%d in list"% a
Insert (i, value) ---Inserts an item vlaue to the list I position, and adds to the tail of the list if I do not
L = [1, 2, 2]
L.insert (1)
print L #[1, 2, 2]
l.insert (MB, 1000)
print L #[1, 100, 2, 2, 100 0]
pops ([i]) ---Return the i position item and remove it from the list, or delete the last item if it is not supplied; if provided, but I is out of the index range, then the exception indexerror
L = [0, 1, 2, 3, 4, 5]
print L.pop () # 5
print L #[0, 1, 2, 3, 4]
print L.pop (1) #1
print L #[0, 2, 3, 4]
try:
L.pop (m)
except Indexerror, ie:
print "Index out of range"
The Remove (value) ---Deletes the first occurrence of value in the list, and if there is no vlaue in the list, the exception valueerror
L = [1, 2, 3, 1, 2, 3]
l.remove (2)
print L #[1, 3, 1, 2, 3]
try:
l.remove (a)
except ValueError, ve:
print "There is no in list"
reverse () ---list inversion
L = [1, 2, 3]
l.reverse ()
print L #[3, 2, 1]
Sort (Cmp=none, Key=none, reverse=false) ---list sorting
Python Library Reference
cmp:cmp Specifies a custom comparison function of two arguments (iterable elements) which Should return a negative, zero or positive number depending on whether the ' the ' the ' argument is considered smaller, than Al to, or larger than the second argument:
Cmp=lambda x,y:cmp (X.lower (), Y.lower ())
Key:key specifie s a function of one argument it used to extract a comparison key from each list element: "Key=str.lower"
Reverse:r Everse is a Boolean value. If set to True, then the "list elements are sorted as if each comparison were. In general, the key and reverse conversion processes are much faster than specifying AN&NBSP;
Equivalent CMP function. This is because the CMP is called multiple The times for each list element while key and reverse the touch of each element only once.
L5 = [5, 1,] L5.sort () Print L5 #[1, 5, m, L6 = ["BCD", "abc", "CDE", "BBB"] l6.sort (cmp = LAMBD A S1, s2:cmp (s1[0],s2[1]) print L6 #[' abc ', ' BBB ', ' BCD ', ' cde '] L7 = ["BCD", "abc", "CDE", "BBB", "FAF"] l7.sort (key = Lambda s:s[1]) print L7 #[' FAF ', ' abc ', ' BBB ', ' BCD ', ' CDE ']