Python (Python) is a dynamic interpreted programming language. Python can be used on Windows, UNIX, MAC, and other operating systems, or on Java and. NET development platforms.
Python logo
[Features]
1 Python is developed in C language, but Python does not have complex data types such as pointers in C language.
2. Python has a strong object-oriented feature and simplifies the implementation of object-oriented. It eliminates protection types, abstract classes, interfaces, and other object-oriented elements.
3. The Python code block is separated by spaces or tab indentation.
4 Python has only 31 reserved words and does not contain semicolons, in, and end tags.
5. Python is a strongly typed language. After a variable is created, it corresponds to a data type. Different types of variables appearing in a unified expression need to be converted.
Python book
[Build a development environment]
1. You can download the installation package from www.python.org and install it through configure, make, and make install.
2. You can also download the ActivePython package at www.activestate.com. (ActivePython is a binary packaging of Python core and common modules. It is a Python development environment released by ActiveState. ActivePython makes Python installation easier and can be applied to various operating systems. ActivePython includes some common Python extensions and programming interfaces in Windows ). For ActivePython, if you are a Windows user, download the msipackage and install it. If you are a unixuser, download the tar.gz package and decompress it directly.
3. Python IDE, including PythonWin, Eclipse + PyDev plugin, Komodo, and EditPlus
[Version]
Python2 and python3 are currently two major versions.
We recommend using python2 in the following two cases:
1. When you cannot fully control the environment you are about to deploy;
2. When you need to use some specific third-party packages or extensions;
Python3 is officially recommended and fully supported in the future. Currently, many functions are only available in python3.
[Hello world]
1 Create hello. py
2. Compile the program:
The code is as follows: |
Copy code |
If _ name _ = '_ main __': Print "hello word" |
3. Run the program:
The code is as follows: |
Copy code |
Python./hello. py |
[Note]
1. Line comment and segment comment are annotated with a space.
2. If you need to use Chinese comments in the code, you must add the following comments at the beginning of the python file:
The code is as follows: |
Copy code |
#-*-Coding: UTF-8 -*- |
3. The following annotations are used to specify the interpreter.
#! /Usr/bin/python
[File type]
1 Python file types are divided into three types: source code, byte code, and optimization code. These operations can be run directly without compilation or connection.
2. The source code uses the. py extension and is explained by python;
3. After the source file is compiled, a file with the extension of. pyc is generated, that is, the compiled byte file. Such files cannot be modified using a text editor. Pyc files are platform-independent and can be run on most operating systems. The following statement can be used to generate a pyc file:
The code is as follows: |
Copy code |
Import py_compile Py_compile.compile ('Hello. Py ') |
4. The optimized source file is suffixed with. pyo, that is, the optimized code. It cannot be directly modified using a text editor. The following command can be used to generate a pyo file:
The code is as follows: |
Copy code |
Python-O-m py_complie hello. py |
Variable]
1. Variables in python do not need to be declared. Variable assignment operations are performed even if the variables are declared and defined.
2. A new value assignment in python creates a new variable. Even if the variable name is the same, the variable IDs are different. You can use the id () function to obtain the variable identifier:
The code is as follows: |
Copy code |
X = 1 Print id (x) X = 2 Print id (x) |
3. If the variable is not assigned a value, python considers that the variable does not exist.
4. Variables defined outside the function can be called global variables. Global variables can be accessed by any function or external file in the file.
5. We recommend that you define global variables at the beginning of the file.
6. You can also put global variables in a special file and reference them through import:
The content in the gl. py file is as follows:
The code is as follows: |
Copy code |
_ A = 1 _ B = 2 |
Reference Global variables in use_global.py:
The code is as follows: |
Copy code |
Import gl Def fun (): Print gl. _ Print gl. _ B Fun () |
[Constant]
No reserved words for defining constants are provided in python. You can define a constant class to implement the constant function.
The code is as follows: |
Copy code |
Class _ const: Class ConstError (TypeError): pass Def _ setattr _ (self, name, vlaue ): If self. _ dict _. has_key (name ): Raise self. ConstError, "Can't rebind const (% s)" % name Self. _ dict _ [name] = value Import sys Sys. modules [_ name _] = _ const () |
[Data type]
1. python numeric types include integer, long integer, floating point, Boolean, and plural.
2. python has no character type
3. python has no common types, and any type is an object.
4. To view the type of a variable, you can use the type class, which can return the type of the variable or create a new type.
5 python has three character string types: single quotation marks, double quotation marks, and three quotation marks. Single quotes and double quotes have the same effect. Python programmers prefer to use single quotes, while C/Java programmers prefer to use double quotes to represent strings. You can enter single quotation marks, double quotation marks, or line breaks among other characters.
[Operators and expressions]
1 python does not support auto-increment and auto-subtraction operators. For example, I ++/I-is incorrect, but I + = 1 is acceptable.
2. 1/2 is equal to 0.5 before python2.5, and 0 after python2.5.
3 is not equal! = Or <>
4 equals =
5. In a logical expression, "and" indicates logical and "or", not indicates non-logical
Control statement]
1. Conditional statement:
The code is as follows: |
Copy code |
If (expression ): Statement 1 Else: Statement 2 |
2 conditional statements:
The code is as follows: |
Copy code |
If (expression ): Statement 1 Elif (expression ): Statement 2 ... Elif (expression ): Statement n Else: Statement m |
3. Conditional nesting:
The code is as follows: |
Copy code |
If (expression 1 ): If (expression 2 ): Statement 1 Elif (Expression 3 ): Statement 2 ... Else: Statement 3 Elif (expression n ): ... Else: ... |
4. python does not have a switch statement.
5 loop statements:
The code is as follows: |
Copy code |
While (expression ): ... Else: ... |
6 loop statements:
The code is as follows: |
Copy code |
For variable in set: ... Else: ... |
7 python does not support loop statements like c (I = 0; I <5; I ++), but it can be simulated using range:
The code is as follows: |
Copy code |
For x in range (0, 5, 2 ): Print x |
[Array-related]
Tuple: a built-in data structure in python. Tuples are composed of different elements. Each element can store different types of data, such as strings, numbers, and even elements. Tuples are write-protected, that is, they cannot be modified after they are created. Tuples often represent a row of data, while elements in tuples represent different data items. You can think of tuples as unmodifiable arrays. An example of creating a tuples is as follows:
The code is as follows: |
Copy code |
Tuple_name = ("apple", "banana", "grape", "orange ") |
List: The list is similar to a group of elements. The list can be added, deleted, or searched, and the value of an element can be modified. A list is an array in the traditional sense. An example of creating a list is as follows:
The code is as follows: |
Copy code |
List = ["apple", "banana", "grage", "orange"] |
You can use the append method to append an element to the end and use remove to delete the element.
3 dictionary: a collection composed of key-value pairs. Values in the dictionary are referenced by keys. Keys and values are separated by colons. Key-value pairs are separated by commas and included in a pair of curly braces. Example:
The code is as follows: |
Copy code |
Dict = {"a": "apple", "B": "banana", "g": "grage", "o": "orange "} |
4. Sequence: a sequence is a set of indexes and slices. Tuples, lists, and strings belong to sequences.
[Function related]
1. A python program consists of a package, a module, and a function. A package is a collection of modules. A module is a collection of functions and classes that handle a certain type of problem.
A 2-pack toolbox is used to complete a specific task.
The 3 package must contain a _ init _. py file, which is used to identify the current folder as a package.
4. python programs are composed of modules. The module organizes a set of related functions or code into a file. A file is a module. A module consists of code, functions, and classes. The import module uses the import statement.
The role of the five packages is to reuse the program.
6. A function is a piece of code that can be called multiple times. The Function definition example is as follows:
The code is as follows: |
Copy code |
Def arithmetic (x, y, operator ): Result = { "+": X + y, "-": X-y, "*": X * y, "/": X/y } |
7. return values can be controlled using return.
[String-related]
1. Format the output:
The code is as follows: |
Copy code |
Format = "% s % d" % (str1, num) Print format |
2. Merge strings with +:
The code is as follows: |
Copy code |
Str1 = "hello" Str2 = "world" Result = str1 + str2 |
3. You can use the index/slice function or the split function to intercept strings.
4. Truncate a string using slices:
The code is as follows: |
Copy code |
Word = "world" Print word [0: 3] |
5 python use = and! = To compare strings. If the two variables are of different types, the results will be different.
[File processing]
1. Simple file processing:
The code is as follows: |
Copy code |
Context = "hello, world" F=file(“hello.txt ", 'w ') F. write (context ); F. close () |
2. You can use readline (), readlines (), and read functions to read files.
3. You can use the write () and writelines () functions to write files.
[Object and class]
1. python defines a class with the class reserved words. The first character of the class name must be capitalized. When the type to be created by a programmer cannot be expressed by a simple type, you need to define the class and then create an object using the defined class. Definition example:
The code is as follows: |
Copy code |
Class Fruit: Def grow (self ): Print "Fruit grow" |
2. When an object is created, it contains three features: the handle, attributes, and methods of the object. How to create an object:
The code is as follows: |
Copy code |
Fruit = Fruit () Fruit. grow () |
3. python does not have a modifier for the protection type.
The four methods can also be divided into public and private methods. Private functions cannot be called by functions other than the class, and private methods cannot be called by external classes or functions.
5. python converts a common function to a static method using the "staticmethod ()" or "@ staticmethod" command. Static methods are equivalent to global functions.
6. The python constructor is named _ init __and the destructor is named _ del __
7 inherited usage:
The code is as follows: |
Copy code |
Class Apple (Fruit ): Def... |
[Connect to mysql]
1. It is very convenient to use the MySQLdb module to operate MySQL databases. The sample code is as follows:
The code is as follows: |
Copy code |
Import OS, sys Import MySQLdb Try: Conn MySQLdb. connect (host = 'localhost', user = 'root', passwd = '', db = 'address' Except t Exception, e: Print e Sys. exit () Cursor = conn. cursor () SQL = 'Insert into address (name, address) values (% s, % s )' Value = ("zhangsan", "haidian"), ("lisi", "haidian ")) Try Cursor.exe cute.pdf (SQL, values) Except t Exception, e: Print e SQL = "select * from address" Cursor.exe cute (SQL) Data = cursor. fetchall () If data For x in data: Print x [0], x [1] Cursor. close () Conn. close () |