Python
Edit Entry
Python (KK English pronunciation: /ˈpaɪθən/) is an object-oriented, interpreted computer programming language. It is also a powerful and complete general-purpose language with more than a decade of development history, mature and stable. Python has the richest and most powerful class libraries among scripting languages, enough to support the vast majority of daily applications. Python has a simple and clear grammar, with rich and powerful class libraries. It is often nicknamed the "glue language" because it can easily connect various modules (especially C/C++) made in other languages. The name Python comes from a comedy. Perhaps the original designers of Python did not expect Python to be so widely used in industry and scientific research.
Quick Navigation
Zhihu Selection
Chinese Name Python
Alias Python language
Designer Guido van Rossum
Honor Programming Language of the Year 2010
English Name python
Release Date 1991
Latest Version 3.4.0, 2.7.8
Overview
Zhihu Selection Latest
Table of Contents
1 Overview Introduction
2 Origin
3 Style Introduction
4 Features and Disadvantages
5 Function Introduction
6 Design Orientation
7 CGI Introduction
Server
Program
Environment Variables
8 Execution Status
9 Basic Syntax
10 Application Introduction
11 Tool Function
12 Version Introduction
13 Development Environment
14 Other Related
1 Overview Introduction Edit
Python is an interpreted, object-oriented, dynamically typed high-level programming language. Since the birth of the Python language in the early 1990s, it has been gradually widely used in system management tasks and web programming. Python has become one of the most popular programming languages. In January 2011, it was rated as the Programming Language of the Year 2010 by the TIOBE Programming Language Ranking. Since 2004, the usage rate of Python has been growing linearly.
Due to the simplicity, readability, and extensibility of the Python language, an increasing number of research institutions abroad are using Python for scientific computing. Some well-known universities have adopted Python to teach programming courses. For example, the Introduction to Computer Science and Programming course at the Massachusetts Institute of Technology uses the Python language for teaching. Many open-source scientific computing software packages provide Python call interfaces. For example, the famous computer vision library OpenCV, the 3D visualization library VTK, and the medical image processing library ITK. And there are more special scientific computing extension libraries for Python. For example, the following three very classic scientific computing extension libraries: NumPy, SciPy, and matplotlib, which respectively provide Python with fast array processing, numerical operations, and drawing functions. Therefore, the development environment composed of the Python language and its numerous extension libraries is very suitable for engineering and technical personnel, researchers to process experimental data, make charts, and even develop scientific computing applications.
When it comes to scientific computing, MATLAB may be the first to be mentioned. However, except for some highly professional toolboxes of MATLAB that cannot be replaced, most of the common functions of MATLAB can be found in the extension libraries of the Python world. Compared with MATLAB, using Python for scientific computing has the following advantages:
● First, MATLAB is a commercial software and is very expensive. However, Python is completely free, and many open-source scientific computing libraries provide Python call interfaces. Users can freely install Python and most of its extension libraries on any computer.
Python LOGO
● Second, compared with MATLAB, Python is a more easy-to-learn and more rigorous programming language. It allows users to write more readable and maintainable code.
● Finally, MATLAB mainly focuses on engineering and scientific computing. However, even in the field of computing, there are often various needs such as file management, interface design, network communication, etc. Python has rich extension libraries and can easily complete various advanced tasks. Developers can use Python to implement various functions required for a complete application program.
English Introduction
Python is an object-oriented interpreted computer programming language, a powerful and all-round language, with more than a decade of development, mature and stable. Python has the richest and most powerful class libraries among scripting languages, enough to support the vast majority of daily applications.
This language has very simple and clear grammatical characteristics, suitable for completing various high-level tasks, and can almost run on all operating systems.
At present, the related technologies based on this language are developing rapidly, the number of users is expanding rapidly, and there are many related resources.
This language has very simple and clear grammatical characteristics, suitable for completing various high-level tasks, and can almost run on all operating systems.
At present, the related technologies based on this language are developing rapidly, the number of users is expanding rapidly, and there are many related resources.
2 Origin Edit
The founder of Python is Guido van Rossum. During the Christmas period in 1989, in Amsterdam, Guido decided to develop a new script interpreter as an inheritance of the ABC language to pass the boring Christmas. The reason for choosing Python (meaning big python) as the name of the program is that he is a fan of a comedy group called Monty Python.
ABC is a teaching language designed by Guido. In Guido's view, the ABC language is very beautiful and powerful, specially designed for non-professional programmers. However, the ABC language was not successful. The reason, according to Guido, is that it is not open. Guido is determined to avoid this mistake in Python. At the same time, he also wants to realize what flashed in ABC but was not realized.
In this way, Python was born in Guido's hands. In fact, the first implementation was on a Mac machine. It can be said that Python developed from ABC, mainly influenced by Modula-3 (another very beautiful and powerful language designed for small groups). And combined with the habits of Unix shell and C.
3 Style Introduction Edit
Style
Python adheres to a clear and uniform style in design, making Python an easy-to-read, easy-to-maintain, and widely used language favored by a large number of users.
The general guiding ideology when the designer was developing was that for a specific problem, there should be one best way to solve it. This is expressed in the Python motto written by Tim Peters (called The Zen of Python) as: There should be one-- and preferably only one --obvious way to do it. This is exactly the opposite of the central idea of the Perl language (another powerful dynamic language with similar functions) TMTOWTDI (There's More Than One Way To Do It).
The author of Python intentionally designs very restrictive grammar, so that bad programming habits (such as the next line of the if statement not indented to the right) cannot pass the compilation. One of the very important ones is the indentation rule of Python.
One difference from most other languages (such as C) is that the boundary of a module is completely determined by the position of the first character of each line in this line (while in C language, the pair of curly braces {} is used to clearly define the boundary of the module, which has nothing to do with the position of characters). This once caused controversy. Since the birth of languages like C, the grammatical meaning of the language has been separated from the arrangement of characters, which was once considered an advancement of a programming language. However, it is undeniable that by forcing programmers to indent (including if, for, function definitions and all places where modules need to be used), Python does make the program more clear and beautiful.
4 Features and Disadvantages Edit
Features:
Simple —— Python is a language representing the idea of simplicity. Reading a good Python program is like reading English, although this English has very strict requirements! This pseudo-code essence of Python is one of its greatest advantages. It allows you to focus on solving problems rather than understanding the language itself.
Easy to Learn —— As you will see soon, Python is extremely easy to get started with. As mentioned earlier, Python has extremely simple grammar.
Fast speed: The underlying layer of Python is written in C language, and many standard libraries and third-party libraries are also written in C, so the running speed is very fast.
Free and Open Source —— Python is one of FLOSS (Free/Open Source Software). Simply put, you can freely distribute copies of this software, read its source code, make changes to it, and use part of it in new free software. FLOSS is based on the concept of a community sharing knowledge. This is one of the reasons why Python is so excellent - it is created and often improved by a group of people who hope to see a better Python.
High-level language —— When you write a program in Python language, you don't need to consider underlying details such as how to manage the memory used by your program.
Portable —— Due to its open-source nature, Python has been ported to many platforms (after being modified to work on different platforms). If you carefully avoid using system-dependent features, all your Python programs can run on any of the following platforms without modification. These platforms include 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, and even PocketPC and Symbian!
Interpreted —— This needs some explanation. A program written in a compiled language such as C or C++ can be converted from a source file (that is, C or C++ language) to a language used by your computer (binary code, that is, 0 and 1). This process is completed through the compiler and different marks and options. When you run your program, the linker/loader software copies your program from the hard disk to the memory and runs it. However, a program written in Python language does not need to be compiled into binary code. You can run the program directly from the source code. Inside the computer, the Python interpreter converts the source code into an intermediate form called bytecode, and then translates it into the machine language used by the computer and runs it. In fact, since you no longer need to worry about how to compile the program, how to ensure that the linker/loader connects the correct libraries, etc., all these make using Python simpler. Since you only need to copy your Python program to another computer, it can work, which also makes your Python program more portable.
Object-oriented —— Python supports both procedural programming and object-oriented programming. In a "procedural" language, a program is built from procedures or just reusable code functions. In an "object-oriented" language, a program is built from objects composed of data and functions. Compared with other main languages such as C++ and Java, Python implements object-oriented programming in a very powerful and simple way.
Extensible —— If you need a part of your key code to run faster or want some algorithms to be not public, you can write part of your program in C or C++, and then use them in your Python program.
Embeddable —— You can embed Python into your C/C++ program, thus providing script functions to your program users.
Rich Libraries —— The Python standard library is indeed very large. It can help you handle various tasks, including regular expressions, document generation, unit testing, threads, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, password systems, GUI (graphical user interface), Tk, and other system-related operations. Remember, as long as Python is installed, all these functions are available. This is called the "full-featured" concept of Python. In addition to the standard library, there are many other high-quality libraries, such as wxPython, Twisted, and Python Imaging Library, etc.
Standardized code: Python uses forced indentation to make the code have good readability. And a program written in Python language does not need to be compiled into binary code.
Summary —— Python is indeed a very wonderful and powerful language. It reasonably combines high performance with the characteristics of making programming simple and interesting.
Disadvantages:
Single-line statements and command-line output problems: Many times, a program cannot be written as a single line, such as import sys;for i in sys.path:print i. However, Perl and awk have no such restrictions and can more conveniently complete simple programs in the shell without having to write a.py file like Python.
Unique grammar
This may not be called a limitation, but the way it uses indentation to distinguish the relationship between statements still confuses many beginners. Even very experienced Python programmers may fall into traps. The most common situation is that the mixing of tab and space will cause errors, and this is indistinguishable to the naked eye.
Untyped
As a dynamic language, creating and using variables anytime and anywhere is a great convenience that Python brings us. However, it will also make the program not rigorous, and some errors may only appear during running. Therefore, when programming in Python, you need to have a clear understanding of the type. This also makes the IDE tools of Python unable to provide convenient automatic completion and other functions.
The statement about "untyped" is completely wrong. It is obviously written by someone who doesn't understand Python. Python is a "strongly typed" and "dynamically bound" language.
Slow running speed: This refers to compared with C and C++.
5 Function Introduction Edit
Python has a powerful standard library. The core of the Python language only contains common types and functions such as numbers, strings, lists, dictionaries, and files, while the Python standard library provides additional functions such as system management, network communication, text processing, database interfaces, graphics systems, and XML processing. The Python standard library has clear named interfaces and good documentation, and is very easy to learn and use.
The Python community provides a large number of third-party modules, which are used in the same way as the standard library. Their functions cover everything, covering multiple fields such as scientific computing, web development, database interfaces, and graphics systems, and most of them are mature and stable. Third-party modules can be written in Python or C language. SWIG and SIP are often used to convert C language-written program libraries into Python modules. The Boost C++ Libraries contain a set of libraries, Boost.Python, which enables programs written in Python or C++ to call each other. With the large number of tools based on the standard library, being able to use low-level languages such as C and being able to act as interfaces for other libraries, Python has become a powerful "glue language" between other languages and tools.
The main functions of the Python standard library are:
Text processing, including text formatting, regular expression matching, text difference calculation and merging, Unicode support, binary data processing, etc.
File processing, including file operations, creating temporary files, file compression and archiving, operating configuration files, etc.
Operating system functions, including thread and process support, IO multiplexing, date and time processing, calling system functions, writing logs (logging), etc.
Network communication, including network sockets, SSL encrypted communication, asynchronous network communication, etc.
Network protocols, supporting multiple network protocols such as HTTP, FTP, SMTP, POP, IMAP, NNTP, XMLRPC, and providing a framework for writing network servers.
W3C format support, including processing of HTML, SGML, XML.
Other functions, including internationalization support, mathematical operations, HASH, Tkinter, etc.
6 Design Orientation Edit
The design philosophy of Python is "elegant", "clear", and "simple". Therefore, the concept in the Perl language that "there are always multiple ways to do the same thing" is usually intolerable to Python developers. The philosophy of Python developers is "use one way, preferably only one way to do one thing". When designing the Python language, if there are multiple choices, Python developers generally refuse fancy grammars and choose clear grammars with no or few ambiguities. Due to this difference in design concepts, Python source code is usually considered to have better readability than Perl and can support large-scale software development. These guidelines are called Python maxims. Running import this in the Python interpreter can get the complete list.
Python developers try to avoid immature or unimportant optimizations. Some patches to speed up running for non-important parts are usually not merged into Python. So many people think Python is slow. However, according to the 80-20 rule, most programs do not require high speed. In some cases where high running speed is required, Python designers tend to use JIT technology, or rewrite this part of the program in C/C++ language. The available JIT technology is PyPy.
Python is a fully object-oriented language. Functions, modules, numbers, strings are all objects. And it fully supports inheritance, overloading, derivation, multiple inheritance, which is beneficial to enhancing the reusability of source code. Python supports overloading operators and dynamic typing. Compared with traditional functional programming languages such as Lisp, Python provides only limited support for functional design. There are two standard libraries (functools, itertools) that provide time-tested functional programming tools from Haskell and Standard ML.
Although Python may be roughly classified as a "script language" (script language), in fact, some large-scale software development plans such as Zope, Mnet, and BitTorrent, and Google also use it extensively. Python supporters prefer to call it a high-level dynamic programming language because "script language" generally refers to a language that only performs simple programming tasks, such as shell script, VBScript, etc., which can only handle simple tasks, and cannot be compared with Python.
Python itself is designed to be extensible. Not all features and functions are integrated into the language core. Python provides rich APIs and tools, so that programmers can easily use C language, C++, Cython to write extension modules. The Python compiler itself can also be integrated into other programs that need a scripting language. Therefore, many people also use Python as a "glue language" (glue language). Use Python to integrate and encapsulate programs written in other languages. In many projects inside Google, such as Google Engine, use C++ to write parts with extremely high performance requirements, and then use Python or Java/Go to call the corresponding modules. Alex Martelli, the author of "Python Technical Manual", said: "It's hard to say, but in 2004, Python was already used inside Google. Google recruited many Python experts, but it had already decided to use Python before that. Their purpose was Python where we can, C++ where we must, use C++ in the occasion of manipulating hardware, and use Python in the occasion of rapid development."
7 CGI Introduction Edit
CGI is currently maintained by NCSA,
CGI (Common Gateway Interface), a common gateway interface, it is a program that runs on the server such as an HTTP server and provides an interface with the client HTML page.
CGI programs can be Python scripts, Perl scripts, Shell scripts, C or C++ programs, etc.
Server
Before you do CGI programming, make sure your web server supports CGI and has configured the handler for CGI.
All HTTP servers execute CGI programs and are stored in a pre-configured directory. This directory is called the CGI directory, and by convention, it is named the /var/www/cgi-bin directory.
The extension of CGI files is.cgi, and Python can also use the.py extension.
By default, the cgi-bin directory configured to run CGI scripts on Linux servers is /var/www.
If you want to specify other directories to run CGI scripts, you can modify the httpd.conf configuration file,
1
2
3
4
5
6
7
8
9
<Directory"/var/www/cgi-bin">
AllowOverrideNone
OptionsExecCGI
Orderallow,deny
Allowfromall
</Directory>
<Directory"/var/www/cgi-bin">
OptionsAll
</Directory>
Program
Use Python to create the first CGI program, the file is named hello.py, and the file is located in the /var/www/cgi-bin directory. The content is as follows,
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/envpython
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("")
print("</head>")
print("<body>")
print("<h2>HelloWord!ThisismyfirstCGIprogram")
print("</body>")
print("</html>")
The above program displays the following result when accessed in the browser:
1
HelloWord!ThisismyfirstCGIprogram
This hello.py script is a simple Python script. The first output content "Content-type:text/html\r\n\r\n" of the script is sent to the browser and informs the browser that the content type to be displayed is "text/html".
Environment Variables
All CGI programs receive the following environment variables,
Variable Name
Description
CONTENT_TYPE
This environment variable's value indicates the MIME type of the passed information. Currently, the environment variable CONTENT_TYPE is generally: application/x-www-form-urlencoded, which means the data comes from an HTML form.
CONTENT_LENGTH
If the way the server and the CGI program pass information is POST, this environment variable is the number of valid bytes that can be read from standard input STDIN. This environment variable must be used when reading the input data.
HTTP_COOKIE Content of the COOKIE in the client machine
HTTP_USER_AGENT Provides client browser information including version number or other proprietary data
PATH_INFO
This environment variable's value indicates other path information immediately after the CGI program name. It often appears as a parameter of the CGI program.
QUERY_STRING
If the way the server and the CGI program pass information is GET, this environment variable's value is the passed information. This information follows the CGI program name and is separated by a question mark '?' between the two.
REMOTE_ADDR
This environment variable's value is the IP address of the client machine sending the request, such as the above 192.168.1.67. This value always exists. And it is the only identifier that the web client needs to provide to the web server, which can be used in the CGI program to distinguish different web clients.
REMOTE_HOST
This environment variable's value contains the hostname of the client machine sending the CGI request. If support for querying is not required, this environment variable does not need to be defined.
REQUEST_METHOD
Provides the method by which the script is called. For scripts using the HTTP/1.0 protocol, only GET and POST are meaningful.
SCRIPT_FILENAME Complete path of the CGI script
SCRIPT_NAME Name of the CGI script
SERVER_NAME This is the hostname, alias, or IP address of your WEB server
SERVER_SOFTWARE This environment variable's value contains the name and version number of the HTTP server that calls the CGI program, for example
The following is a simple CGI script to output the environment variables of CGI:
1
2
3
4
5
#!/usr/bin/pythonimportosprint"Content-type:text/html\r\n\r\n";
print"<fontsize=+1>Environment</font><\br>";
forparaminos.environ.keys():
print"<b>%20s</b>:%s<\br>"
%(param,os.environ)
8 Execution Status Edit
When Python is executed, it first compiles the source code in the.py file into Python byte code (bytecode), and then the Python Virtual Machine (Python Virtual Machine) executes these compiled bytecode. The basic idea of this mechanism is the same as that of Java and.NET. However, the Python Virtual Machine is different from the Java or.NET Virtual Machine. The Python Virtual Machine is a more advanced Virtual Machine. The advanced here does not mean powerful in the usual sense. It does not mean that the Python Virtual Machine is more powerful than the Java or.NET Virtual Machine, but that compared with Java or.NET, the Python Virtual Machine is farther from the real machine. Or it can be said that the Python Virtual Machine is a Virtual Machine with a higher level of abstraction.
The bytecode file compiled based on C Python is usually in.pyc format.
In addition, Python can also run in interactive mode. For example, mainstream operating systems such as Unix/Linux, Mac, and window can directly run the Python interactive environment in the command mode. You can directly issue operation instructions to achieve interactive operations.
9 Basic Syntax Edit
One of the design goals of Python is to make the code have high readability. When it is designed, it tries to use punctuation marks and English words often used in other languages, making the code look neat and beautiful. It does not need to repeatedly write declaration statements like other static languages such as C and Pascal, and there are no special cases and surprises in its grammar like them.
Indentation
Python developers intentionally make programs that violate the indentation rule unable to pass the compilation, so as to force programmers to develop good programming habits. And Python uses indentation to indicate the start and exit of a statement block (Off-side rule), instead of using curly braces or some keywords. Increasing indentation indicates the start of a statement block, and decreasing indentation indicates the exit of a statement block. Indentation has become part of the grammar. For example, the if statement:
Note: The above example is the code of Python 3.0 version, @ represents a space
According to the PEP regulations, 4 spaces must be used to represent each level of indentation (I don't know the regulations of 4 spaces, in actual writing, you can customize the number of spaces, but the number of spaces between each level of indentation must be equal). Using Tab characters and other numbers of spaces can all pass the compilation, but it does not conform to the coding specification. Supporting Tab characters and other numbers of spaces is only for compatibility with very old Python programs and some problematic editors.
Flow Control Statements
if statement, when the condition is true, run the statement block. Often used with else, elif (equivalent to else if) in combination.
for statement, iterate over iterators such as lists, strings, dictionaries, sets, and process each element in the iterator in turn.
while statement, when the condition is true, loop to run the statement block.
try statement. Used with except, finally in combination to handle abnormal situations that occur during program operation.
class statement. Used to define a type.
def statement. Used to define functions and methods of types.
pass statement. Indicates that this behavior is empty and no operation is run.
assert statement. Used to test whether the running condition is satisfied during the program debugging stage.
with statement. The syntax defined after Python 2.6 is to run the statement block in a scenario. For example, encrypt before running the statement block, and decrypt after the statement block runs and exits.
yield statement. Used in iterator functions to return an element. Since the Python 2.5 version. This statement has become an operator.
raise statement. Make an error.
import statement. Import a module or package.
from import statement. Import a module from a package or an object from a module.
import as statement. Assign the imported object to a variable.
in statement. Judge whether an object is in a string/list/tuple.
Expression
The expression writing of Python is similar to C/C++. Only some writing is different.
The main arithmetic operators are similar to C/C++. +, -, *, /, //, **, ~, % respectively represent addition or taking positive, subtraction or taking negative, multiplication, division, integer division, exponentiation, taking complement, taking modulus. >>, << represent right shift and left shift. &, |, ^ represent binary AND, OR, XOR operations. >, <, ==, !=, <=, >= are used to compare the values of two expressions, representing greater than, less than, equal to, not equal to, less than or equal to, greater than or equal to respectively. Among these operators, ~, |, ^, &, <<, >> must be applied to integers.
Python uses and, or, not to represent logical operations.
is, is not are used to compare whether two variables are the same object. in, not in are used to judge whether an object belongs to another object.
Python supports "list comprehension" (list comprehension), for example, calculate the sum of squares from 0 to 9:
>>> sum(x * x for x in range(10))
285
Python uses lambda to represent an anonymous function. The body of an anonymous function can only be an expression. For example:
>>> add=lambda x, y : x + y
>>> add(3,2)
5
Python uses y if cond else x to represent a conditional expression. It means that when cond is true, the value of the expression is y, otherwise the value of the expression is x. It is equivalent to cond?y:x in C++ and Java.
Python distinguishes between list (list) and tuple (tuple) types. The writing of list is , and the writing of tuple is (1,2,3). The elements in the list can be changed, but the elements in the tuple cannot be changed. In some cases, the parentheses of the tuple can be omitted. The tuple has special processing for assignment statements. Therefore, it can be assigned to multiple variables at the same time, for example:
>>> x, y=1,2#Assign values to x and y at the same time, the final result: x=1, y=2
In particular, the following form can be used to exchange the values of two variables:
>>> x, y=y, x #Final result: y=1, x=2
Python uses '(single quote) and "(double quote) to represent strings. Unlike Perl, Unix Shell language, or Ruby, Groovy and other languages, the two symbols have the same function. Generally, if double quotes appear in the string, use single quotes to represent the string; otherwise, use double quotes. If neither appears, choose according to personal preference. \ (backslash) appearing in the string is interpreted as a special character, such as \n representing a newline character. Adding r in front of the expression indicates that Python does not interpret \ appearing in the string. This writing is usually used to write regular expressions or Windows file paths.
Python supports list slicing (list slices), and can obtain a part of the complete list. Types that support slicing operations include str, bytes, list, tuple, etc. Its syntax is... or.... Assuming that the value of the nums variable is , then the following statements are true:
nums == Cut from the element with index 2 to the element with index 5, but does not include the element with index 5.
nums == Cut to the last element.
nums == Cut from the first element to the third last element.
nums == Return all elements. Changing the new list will not affect nums.
nums == Cut from the element with index 1 to the element with index 5 but does not include the element with index 5, and the step size is 2.
Function
Python's functions support recursion, default parameter values, and variable parameters, but do not support function overloading. To enhance the readability of the code, "document strings" (Documentation Strings, or简称docstrings) can be written after the function, used to explain the function's function, the type and meaning of parameters, the type and value range of the return value, etc. The built-in function help() can be used to print the usage help of the function. For example:
>>>def randint(a, b):... "Return random integer in range , including both end points."...>>>help(randint)Help on function randint in module __main__: randint(a, b) Return random integer inrange, including both end points.
Object Method
An object's method refers to a function bound to the object. The syntax for calling an object method is instance.method(arguments). It is equivalent to calling Class.method(instance, arguments). When defining an object method, you must explicitly define the first parameter. Generally, this parameter name is self, used to access the internal data of the object. Here, self is equivalent to the this variable in C++ and Java, but we can also use any other legal parameter name, such as this and mine, etc. self is not exactly the same as this in C++ and Java. It can be regarded as a habitual usage. We can pass in any other legal name, for example:
Python recognizes some special method names starting with "__" and ending with "__", which are used to implement operator overloading and implement various special functions.
Type
Python adopts a dynamic type system. At compile time, Python will not check whether an object has the called method or attribute, but will make a check until runtime. Therefore, operations on objects may throw exceptions. However, although Python adopts a dynamic type system, it is also strongly typed. Python prohibits undefined operations, such as adding a number to a string.
Like other object-oriented languages, Python allows programmers to define types. Constructing an object only needs to be called like a function, for example, for the previously defined Fish type, use Fish(). The type itself is also an object of the special type type (the type type itself is also a type object), this special design allows reflection programming on the type.
Python has rich built-in data types. Compared with Java and C++, these data types effectively reduce the length of the code. The following list briefly describes the Python built-in data types (suitable for Python 3.x):
Type
Description
Example
Remarks
str A non-changeable sequence composed of characters
'Wikipedia'
"Wikipedia"
"""Spanning
multiple
lines"""
In Python 3.x, the string is composed of Unicode characters
bytes A non-changeable sequence composed of bytes b'Some,ASCII'b",Some,ASCII"
list A changeable sequence that can contain multiple types
tuple A non-changeable sequence that can contain multiple types (4,0,'string',True)
set,frozenset Similar to the concept of a set in mathematics, unordered, each element is unique
{4.0, 'string', True}
frozenset()
dict A changeable sequence composed of key-value pairs {'key1':,1,0,3:,False}
int Integers with unlimited precision 42
float Floating-point numbers, precision related to the system 3.1415927
complex Complex numbers 3+2,7j
bool Logical values, only two values: true, false TrueFalse
In addition to various data types, the Python language also uses types to represent functions, modules, types themselves, object methods, compiled Python code, runtime information, etc. Therefore, Python has strong dynamicity.
Mathematical Operations
Python uses operators similar to C and Java to support mathematical operations of integers and floating-point numbers. It also supports complex number operations and integer operations with infinite digits (actually limited by the computer's ability). Except for the absolute value function abs(), most mathematical functions are in the math and cmath modules. The former is used for real number operations, and the latter is used for complex number operations. You need to import them first, for example:
>>>importmath>>>print(math.sin(math.pi/2))1.0
The fractions module is used to support fraction operations; the decimal module is used to support high-precision floating-point number operations.
Python defines that the value of the remainder operation a % b is in the open interval . This is a very common definition. However, it actually depends on the definition of integer division. In order for the equation: b * (a // b) + a % b = a to be true all the time, the integer division operation needs to take values in the direction of negative infinity. For example, the result of 7 // 3 is 2, while the result of (-7) // 3 is -3. This algorithm is different from many other programming languages, and needs to be noted that their integer division operations will take values in the direction of 0.
Python allows writing two comparison operations consecutively like the common writing in mathematics. For example, a < b < c is equivalent to a < b and b < c. The result of C++ is different from Python. First, it will calculate a < b, and get one of 0 or 1 according to the size of the two, and then compare with c.
10 Application Introduction Edit
System programming: Provide API (Application Programming Interface), can conveniently perform system maintenance and management, one of the iconic languages under Linux, and is an ideal programming tool for many system administrators.
Graphics processing: There are PIL, Tkinter and other graphics libraries to support, can conveniently perform graphics processing.
Mathematical processing: The NumPy extension provides a large number of interfaces with many standard mathematical libraries.
Text processing: The re module provided by Python can support regular expressions, and also provides SGML, XML analysis modules. Many programmers use Python to develop XML programs.
Database programming: Programmers can communicate with databases such as Microsoft SQL Server, Oracle, Sybase, DB2, Mysql, SQLite through modules that follow the Python DB-API (Database Application Programming Interface) specification. Python has a Gadfly module by itself, which provides a complete SQL environment.
Network programming: Provide rich module support for sockets programming, and can conveniently and quickly develop distributed application programs. Many large-scale software development plans such as Zope, Mnet, and BitTorrent. Google are using it extensively.
Web programming: The development language of the application supports the latest XML technology.
Multimedia application: Python's PyOpenGL module encapsulates the "OpenGL Application Programming Interface" and can perform 2D and 3D image processing. The PyGame module can be used to write game software.
pymo engine: PYMO is full name Python memories off, is a game engine running on Symbian S60V3, Symbian3, S60V5, Symbian3, Android systems for AVG games. Because it is developed based on the Python 2.0 platform and is suitable for creating AVG games in the style of Memories Off (memories off), it is named PYMO.
Hacker programming: Python has a hack library, which has the functions you are familiar with or not familiar with, but lacks a sense of achievement.
Write a simple crawler with Python
First, you need to obtain the corresponding HTML source code through the urllib2 module.
import urllib2
url='http://www.baidu.com/s?wd=cloga'
content=urllib2.urlopen(url).read()
With the above three sentences, the source code of the URL can be stored in the content variable, and its type is character type.
Next, you need to extract the content we need from this pile of HTML source code. Use Chrome to view the code of the corresponding content (you can also use Firebug of Firefox).
You can see that the information of the url is stored in the span tag, and regular expressions can be used to obtain the information.
Pylons-Web application framework
Zope- Application server
Plone- Content management system
Django- Web application framework that encourages rapid development
Uliweb- Lightweight Web framework developed by Chinese people
TurboGears- Another fast Web application development framework
Twisted--Python's network application framework
Python Wikipedia Robot Framework- MediaWiki's robot program
MoinMoinWiki- Wiki program written in Python
flask- Micro Web framework in Python
Webpy- Micro Web framework in Python
Bottle- Micro Web framework in Python
EVE- The online game EVE is developed a lot using Python
Reddit - Social sharing website
Dropbox - File sharing service
Pylons - Web application framework
TurboGears - Another fast Web application development framework
Fabric - A library program used to manage hundreds of thousands of Linux hosts
Trac - BUG management system written in Python
Mailman - Email list software written in Python
Mezzanine - Content management system system based on Django
Blender - Open-source 3D drawing software developed in C and Python
11 Tool Function Edit
Tkinter
Python's default graphical interface interface. Tkinter is a Python module that interfaces with Tk. The Tkinter library provides an interface to the Tk API, and it belongs to the GUI tool group of Tcl/Tk.
PyGTK
GTK+ library for Python GUI program development. GTK is the library used to implement GIMP and Gnome.
PyQt
Qt development library for Python. QT is the library that implements the KDE environment, composed of a series of modules, including qt, qtcanvas, qtgl, qtnetwork, qtsql, qttable, qtui and qtxml, containing 300 classes and more than 5750 functions and methods. PyQt also supports a module called qtext, which contains a QScintilla library. This library is the Qt interface of the Scintillar editor class.
wxPython
GUI programming framework. People who are familiar with MFC will like it very much. It is almost the same architecture (for beginners or users with low design requirements, using Boa Constructor can conveniently and quickly develop wxPython).
PIL
Python provides powerful graphic processing capabilities and provides extensive graphic file format support. This library can perform conversion, printing, and display of graphic formats. It can also perform some graphic effect processing, such as zooming, shrinking, and rotating of graphics. It is a powerful tool for Python users to process images.
Psyco
A Python code accelerator that can increase the execution speed of Python code to the level of a compiled language.
xmpppy
The XMPP protocol developed by the Jabber server. Google Talk is also an IM system using the XMPP protocol. There is an xmpppy module in Python to support this protocol. That is to say, we can communicate with the Jabber server through this module. Isn't it very cool.
PyMedia
A Python module for multimedia operations. It provides rich and simple interfaces for multimedia processing (wav, mp3, ogg, avi, divx, dvd, cdda etc). Can be used on Windows and Linux platforms.
Pmw
Python megawidgets, Python super GUI component set, a high-level GUI component built in Python using the Tkinter module. Each Pmw combines one or more Tkinter components to implement more useful and complex functions.
PyXML
A toolkit for parsing and processing XML documents in Python. The 4DOM in the package is completely compatible with the W3C DOM specification. It contains the following contents:
xmlproc: A compliant XML parser. Expat: A fast, non-validating XML parser. There are other同级别的 ones such as PyHtml PySGML.
PyGame
A module for multimedia development and game software development.
PyOpenGL
The module encapsulates the "OpenGL Application Programming Interface". Through this module, Python programmers can integrate 2D and 3D graphics in the program.
NumPy, NumArray, SAGE
NumArray is an extension library of Python, mainly used to handle fixed-type arrays of any dimension. Simply put, it is a matrix library. Its underlying code is written in C, so the speed advantage is obvious. SAGE is a mathematical software package integrated based on NumPy and several other tools. The goal is to replace tools such as Magma, Maple, Mathematica, and Matlab.
MySQLdb
Used to connect to the MySQL database. There is also the ZMySQLDA module for zope, through which you can connect to the mysql database in zope.
Sqlite3
Used to connect to the sqlite database.
Python-ldap
Provides a set of object-oriented APIs, which can conveniently access the ldap directory service in Python, and it is based on OpenLDAP2.x.
smtplib
Send emails.
ftplib
Defines the FTP class and some methods for client-side ftp programming. If you want to know the detailed content of the ftp protocol, please refer to RFC959.
12 Version Introduction Edit
The main versions of Python are 2.x and 3.x, and currently 2.x is used more. Here is an article about "whether beginners learn Python 2 or Python 3?" which is very good, you can refer to it: http://www.pythontab.com/html/2012/pythonjichu_1220/11.html
The Python 3.0 version is often called Python 3000, or abbreviated as Py3k. Compared with the early versions of Python, this is a major upgrade. In order to not bring in too much baggage, Python 3.0 did not consider backward compatibility when designing. Many programs designed for early Python versions cannot run normally on Python 3.0. In order to take into account existing programs, Python 2.6 is used as a transition version, which basically uses the syntax and library of Python 2.x, and at the same time considers the migration to Python 3.0, allowing the use of some syntax and functions of Python 3.0. Programs that can run normally on Python 2.6 without warnings based on early Python versions can be seamlessly migrated to Python 3.0 through a 2 to 3 conversion tool.
New Python programs are recommended to use the syntax of the Python 3.0 version. Unless the running environment cannot install Python 3.0 or the program itself uses third-party libraries that do not support Python 3.0. Currently, third-party libraries that do not support Python 3.0 include Django, Twisted, py2exe, PIL, etc. Most third-party libraries are working hard to be compatible with the Python 3.0 version. Even if Python 3.0 cannot be used immediately, it is recommended to write programs compatible with the Python 3.0 version, and then run them with Python 2.6, Python 2.7. Python 2.7 is determined to be the last Python 2.x version. In addition to supporting Python 2.x syntax, it also supports part of Python 3.1 syntax.
The Python 3.0 version is often called Python 3000, or abbreviated as Py3k. Compared with the early versions of Python, this is a major upgrade. In order to not bring in too much baggage, Python 3.0 did not consider backward compatibility when designing. Many programs designed for early Python versions cannot run normally on Python 3.0. In order to take into account existing programs, Python 2.6 is used as a transition version, which basically uses the syntax and library of Python 2.x, and at the same time considers the migration to Python 3.0, allowing the use of some syntax and functions of Python 3.0. Programs that can run normally on Python 2.6 without warnings based on early Python versions can be seamlessly migrated to Python 3.0 through a 2 to 3 conversion tool.
New Python programs are recommended to use the syntax of the Python 3.0 version. Unless the running environment cannot install Python 3.0 or the program itself uses third-party libraries that do not support Python 3.0. Third-party libraries that do not support Python 3.0 include Django, Twisted, py2exe, PIL, etc. Most third-party libraries are working hard to be compatible with the Python 3.0 version. Even if Python 3.0 cannot be used immediately, it is recommended to write programs compatible with the Python 3.0 version, and then run them with Python 2.6, Python 2.7. Python 2.7 is determined to be the last Python 2.x version. In addition to supporting Python 2.x syntax, it also supports part of Python 3.1 syntax.
The changes in Python 3.0 are mainly in the following aspects:
The most noticeable change is that the print statement is gone, replaced by the print() function. The 2to3 tool can be used to automatically convert print statements. Python 2.6 and Python 2.7 partially support this form of print syntax. In Python 2.6 and Python 2.7, the following three forms are equivalent:
print"fish"print("fish")#Note that there is a space after printprint("fish")#print() cannot have any other parameters
However, Python 2.6 has actually supported the new print() syntax. The method is:
from__future__import print_functionprint("fish","panda", sep=', ')
The new str type represents a Unicode string, equivalent to the unicode type in the Python 2.x version. The byte sequence is represented by a syntax like b"abc", represented by the bytes class, equivalent to the str type in the Python 2.x version. The two types can no longer be implicitly and automatically converted. Therefore, in Python 3.x, "fish"+b"panda" is wrong. The correct way is "fish"+b"panda".decode("utf-8"). Python 2.6 can automatically recognize the byte sequence as a Unicode string. The method is:
from__future__import unicode_literalsprint(repr("fish"))
The division operator / in Python 3.x always returns a floating-point number. In Python 2.6, it will judge whether the dividend and divisor are integers. If they are integers, it will return an integer value, equivalent to integer division; if they are floating-point numbers, it will return a floating-point value. In order to make Python 2.6 return a floating-point value uniformly, you can:
from__future__import divisionprint(3/2)
The syntax for catching exceptions is changed from except exc, var to except exc as var. Using the syntax except (exc1, exc2) as var can catch multiple types of exceptions at the same time. Python 2.6 has supported these two grammars.
Dictionary comprehensions (Dictionary comprehensions) {expr1: expr2 for k, v in d}, this syntax is equivalent to:
result={}for k, v in d.items(): result=expr2return result
The new writing of set (set): {1,2,3,4}. Note that {} still represents an empty dictionary (dict).
Octal numbers must be written as 0o777, and the original form 0777 is no longer available; binary must be written as 0b111. A new bin() function is added to convert an integer into a binary string. Python 2.6 has supported these two grammars.
dict.keys(), dict.values(), dict.items(), map(), filter(), range(), zip() no longer return lists, but iterators.
If there is no clearly defined and meaningful order between two objects. Comparing them with <, >, <=, >= will throw an exception. For example, 1 < "" will return True in Python 2.6, but will throw an exception in Python 3.0. The cmp(), instance.__cmp__() functions have been deleted.
The parameters and return values of the function can be annotated. This feature can facilitate IDE to perform more in-depth analysis of the source code. For example:
def sendMail(from_:"nobody@example .com", \ to:"somebody@example .com", \ title:"hello", \ body:"Just say hello to you.") ->True: pass
According to PEP8, multiple modules are renamed:
Old name
New name
_winreg winreg
ConfigParser configparser
copy_reg copyreg
Queue queue
SocketServer socketserver
repr reprlib
The StringIO module is merged into the new io module. Modules such as new, md5, gopherlib are deleted. Python 2.6 has supported the new io module.
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib are merged into the http package.
The exec statement is canceled, leaving only the exec() function. Python 2.6 has supported the exec() function.
Basically, programs that use Python 3.0 syntax and run on Python 2.6, Python 2.7 can be written.
13 Development Environment Edit
●IDLE: Python built-in IDE (provided with the python installation package)
●PyCharm: See Baidu Encyclopedia PyCharm, developed by the famous JetBrains company, with a complete set of tools that can help users improve their efficiency when developing in the Python language, such as debugging, syntax highlighting, Project management, code jumping, intelligent prompting, auto-completion, unit testing, version control. In addition, this IDE provides some advanced functions to support professional web development under the Django framework.
●Komodo and Komodo Edit: The latter is a free and streamlined version of the former
●PythonWin: Both ActivePython or pywin32 provide this IDE, only applicable to Windows
●SPE (Stani's Python Editor): A free software with more functions, based on wxPython
●Ulipad: A free software with complete functions, based on wxPython; the author is Chinese Python expert limodou
●WingIDE: Probably the most comprehensive IDE, but not free software (educational users and open-source users can apply for a free key)
●Eric: Free software based on PyQt, powerful. The full name is: The Eric Python IDE
●DrPython
●PyScripter: A lightweight open-source Python IDE developed with Delphi, supporting Python 2.6 and 3.0.
●PyPE: An open-source cross-platform Python IDE.
●bpython: A lightweight Python interpreter developed using the curses library under Unix-like operating systems. Syntax prompting function.
●eclipse + pydev plug-in: convenient for debugging programs
●emacs: has built-in Python support, and functions such as auto-completion and refactor need plug-in support
●Vim: The latest 7.3 version can be compiled with Python support when compiling, providing Python code auto-prompt support
●Visual Studio 2003 + VisualPython: only applicable to Windows, has stopped maintenance, and has poor functions
●SlickEdit
●Visual Studio 2010 + Python Tools for Visual Studio
●TextMate
●Netbeans IDE
●Sublime
In addition, general programmer text editor software such as EditPlus, UltraEdit, PSPad can also provide certain support for Python code editing, such as code automatic coloring, comment shortcuts, etc., but whether it can be regarded as an integrated development environment level is still to be evaluated.
14 Other Related Edit
Interpreter
Python is a cross-platform scripting language. Python specifies a Python grammar rule, and the interpreter that implements the Python grammar rule becomes the Python interpreter.
CPython (Classic Python, that is, the original Python implementation, which is called CPython when it needs to be distinguished from other implementations; or interpreted as a Python implemented in C language). This is the most commonly used Python version.
Jython (formerly JPython; Python implemented in Java language, which has been officially released). Jython can directly call various function libraries of Java.
PyPy (Python written in Python language)
IronPython (Python implementation for.NET and ECMA CLI). IronPython can directly call various function libraries of the.net platform. Python programs can be compiled into.net programs.
ZhPy (Zhou Python) (Python language that supports writing programs using traditional/ simplified Chinese statements)
Learning Websites
1. PythonTab Chinese Website
2. Python Enthusiasts Forum
3. Pythoner Online Interaction Platform
4. One Person One Python
References:
1.
Simple Introduction to Python
2.
Introduction to Python
3.
Whether Beginners Learn Python 2 or Python 3
Extended Reading:
1.
Introduction to Python
2.
Introduction to Python Entry
3.
Detailed Explanation of Python Tool Introduction
Entry Tags:
Programming Language, Computer, Computer, Python, Open Source
[ Last edited by zzz19760225 on 2016-9-22 at 17:35 ]
Edit Entry
Python (KK English pronunciation: /ˈpaɪθən/) is an object-oriented, interpreted computer programming language. It is also a powerful and complete general-purpose language with more than a decade of development history, mature and stable. Python has the richest and most powerful class libraries among scripting languages, enough to support the vast majority of daily applications. Python has a simple and clear grammar, with rich and powerful class libraries. It is often nicknamed the "glue language" because it can easily connect various modules (especially C/C++) made in other languages. The name Python comes from a comedy. Perhaps the original designers of Python did not expect Python to be so widely used in industry and scientific research.
Quick Navigation
Zhihu Selection
Chinese Name Python
Alias Python language
Designer Guido van Rossum
Honor Programming Language of the Year 2010
English Name python
Release Date 1991
Latest Version 3.4.0, 2.7.8
Overview
Zhihu Selection Latest
Table of Contents
1 Overview Introduction
2 Origin
3 Style Introduction
4 Features and Disadvantages
5 Function Introduction
6 Design Orientation
7 CGI Introduction
Server
Program
Environment Variables
8 Execution Status
9 Basic Syntax
10 Application Introduction
11 Tool Function
12 Version Introduction
13 Development Environment
14 Other Related
1 Overview Introduction Edit
Python is an interpreted, object-oriented, dynamically typed high-level programming language. Since the birth of the Python language in the early 1990s, it has been gradually widely used in system management tasks and web programming. Python has become one of the most popular programming languages. In January 2011, it was rated as the Programming Language of the Year 2010 by the TIOBE Programming Language Ranking. Since 2004, the usage rate of Python has been growing linearly.
Due to the simplicity, readability, and extensibility of the Python language, an increasing number of research institutions abroad are using Python for scientific computing. Some well-known universities have adopted Python to teach programming courses. For example, the Introduction to Computer Science and Programming course at the Massachusetts Institute of Technology uses the Python language for teaching. Many open-source scientific computing software packages provide Python call interfaces. For example, the famous computer vision library OpenCV, the 3D visualization library VTK, and the medical image processing library ITK. And there are more special scientific computing extension libraries for Python. For example, the following three very classic scientific computing extension libraries: NumPy, SciPy, and matplotlib, which respectively provide Python with fast array processing, numerical operations, and drawing functions. Therefore, the development environment composed of the Python language and its numerous extension libraries is very suitable for engineering and technical personnel, researchers to process experimental data, make charts, and even develop scientific computing applications.
When it comes to scientific computing, MATLAB may be the first to be mentioned. However, except for some highly professional toolboxes of MATLAB that cannot be replaced, most of the common functions of MATLAB can be found in the extension libraries of the Python world. Compared with MATLAB, using Python for scientific computing has the following advantages:
● First, MATLAB is a commercial software and is very expensive. However, Python is completely free, and many open-source scientific computing libraries provide Python call interfaces. Users can freely install Python and most of its extension libraries on any computer.
Python LOGO
● Second, compared with MATLAB, Python is a more easy-to-learn and more rigorous programming language. It allows users to write more readable and maintainable code.
● Finally, MATLAB mainly focuses on engineering and scientific computing. However, even in the field of computing, there are often various needs such as file management, interface design, network communication, etc. Python has rich extension libraries and can easily complete various advanced tasks. Developers can use Python to implement various functions required for a complete application program.
English Introduction
Python is an object-oriented interpreted computer programming language, a powerful and all-round language, with more than a decade of development, mature and stable. Python has the richest and most powerful class libraries among scripting languages, enough to support the vast majority of daily applications.
This language has very simple and clear grammatical characteristics, suitable for completing various high-level tasks, and can almost run on all operating systems.
At present, the related technologies based on this language are developing rapidly, the number of users is expanding rapidly, and there are many related resources.
This language has very simple and clear grammatical characteristics, suitable for completing various high-level tasks, and can almost run on all operating systems.
At present, the related technologies based on this language are developing rapidly, the number of users is expanding rapidly, and there are many related resources.
2 Origin Edit
The founder of Python is Guido van Rossum. During the Christmas period in 1989, in Amsterdam, Guido decided to develop a new script interpreter as an inheritance of the ABC language to pass the boring Christmas. The reason for choosing Python (meaning big python) as the name of the program is that he is a fan of a comedy group called Monty Python.
ABC is a teaching language designed by Guido. In Guido's view, the ABC language is very beautiful and powerful, specially designed for non-professional programmers. However, the ABC language was not successful. The reason, according to Guido, is that it is not open. Guido is determined to avoid this mistake in Python. At the same time, he also wants to realize what flashed in ABC but was not realized.
In this way, Python was born in Guido's hands. In fact, the first implementation was on a Mac machine. It can be said that Python developed from ABC, mainly influenced by Modula-3 (another very beautiful and powerful language designed for small groups). And combined with the habits of Unix shell and C.
3 Style Introduction Edit
Style
Python adheres to a clear and uniform style in design, making Python an easy-to-read, easy-to-maintain, and widely used language favored by a large number of users.
The general guiding ideology when the designer was developing was that for a specific problem, there should be one best way to solve it. This is expressed in the Python motto written by Tim Peters (called The Zen of Python) as: There should be one-- and preferably only one --obvious way to do it. This is exactly the opposite of the central idea of the Perl language (another powerful dynamic language with similar functions) TMTOWTDI (There's More Than One Way To Do It).
The author of Python intentionally designs very restrictive grammar, so that bad programming habits (such as the next line of the if statement not indented to the right) cannot pass the compilation. One of the very important ones is the indentation rule of Python.
One difference from most other languages (such as C) is that the boundary of a module is completely determined by the position of the first character of each line in this line (while in C language, the pair of curly braces {} is used to clearly define the boundary of the module, which has nothing to do with the position of characters). This once caused controversy. Since the birth of languages like C, the grammatical meaning of the language has been separated from the arrangement of characters, which was once considered an advancement of a programming language. However, it is undeniable that by forcing programmers to indent (including if, for, function definitions and all places where modules need to be used), Python does make the program more clear and beautiful.
4 Features and Disadvantages Edit
Features:
Simple —— Python is a language representing the idea of simplicity. Reading a good Python program is like reading English, although this English has very strict requirements! This pseudo-code essence of Python is one of its greatest advantages. It allows you to focus on solving problems rather than understanding the language itself.
Easy to Learn —— As you will see soon, Python is extremely easy to get started with. As mentioned earlier, Python has extremely simple grammar.
Fast speed: The underlying layer of Python is written in C language, and many standard libraries and third-party libraries are also written in C, so the running speed is very fast.
Free and Open Source —— Python is one of FLOSS (Free/Open Source Software). Simply put, you can freely distribute copies of this software, read its source code, make changes to it, and use part of it in new free software. FLOSS is based on the concept of a community sharing knowledge. This is one of the reasons why Python is so excellent - it is created and often improved by a group of people who hope to see a better Python.
High-level language —— When you write a program in Python language, you don't need to consider underlying details such as how to manage the memory used by your program.
Portable —— Due to its open-source nature, Python has been ported to many platforms (after being modified to work on different platforms). If you carefully avoid using system-dependent features, all your Python programs can run on any of the following platforms without modification. These platforms include 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, and even PocketPC and Symbian!
Interpreted —— This needs some explanation. A program written in a compiled language such as C or C++ can be converted from a source file (that is, C or C++ language) to a language used by your computer (binary code, that is, 0 and 1). This process is completed through the compiler and different marks and options. When you run your program, the linker/loader software copies your program from the hard disk to the memory and runs it. However, a program written in Python language does not need to be compiled into binary code. You can run the program directly from the source code. Inside the computer, the Python interpreter converts the source code into an intermediate form called bytecode, and then translates it into the machine language used by the computer and runs it. In fact, since you no longer need to worry about how to compile the program, how to ensure that the linker/loader connects the correct libraries, etc., all these make using Python simpler. Since you only need to copy your Python program to another computer, it can work, which also makes your Python program more portable.
Object-oriented —— Python supports both procedural programming and object-oriented programming. In a "procedural" language, a program is built from procedures or just reusable code functions. In an "object-oriented" language, a program is built from objects composed of data and functions. Compared with other main languages such as C++ and Java, Python implements object-oriented programming in a very powerful and simple way.
Extensible —— If you need a part of your key code to run faster or want some algorithms to be not public, you can write part of your program in C or C++, and then use them in your Python program.
Embeddable —— You can embed Python into your C/C++ program, thus providing script functions to your program users.
Rich Libraries —— The Python standard library is indeed very large. It can help you handle various tasks, including regular expressions, document generation, unit testing, threads, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, password systems, GUI (graphical user interface), Tk, and other system-related operations. Remember, as long as Python is installed, all these functions are available. This is called the "full-featured" concept of Python. In addition to the standard library, there are many other high-quality libraries, such as wxPython, Twisted, and Python Imaging Library, etc.
Standardized code: Python uses forced indentation to make the code have good readability. And a program written in Python language does not need to be compiled into binary code.
Summary —— Python is indeed a very wonderful and powerful language. It reasonably combines high performance with the characteristics of making programming simple and interesting.
Disadvantages:
Single-line statements and command-line output problems: Many times, a program cannot be written as a single line, such as import sys;for i in sys.path:print i. However, Perl and awk have no such restrictions and can more conveniently complete simple programs in the shell without having to write a.py file like Python.
Unique grammar
This may not be called a limitation, but the way it uses indentation to distinguish the relationship between statements still confuses many beginners. Even very experienced Python programmers may fall into traps. The most common situation is that the mixing of tab and space will cause errors, and this is indistinguishable to the naked eye.
Untyped
As a dynamic language, creating and using variables anytime and anywhere is a great convenience that Python brings us. However, it will also make the program not rigorous, and some errors may only appear during running. Therefore, when programming in Python, you need to have a clear understanding of the type. This also makes the IDE tools of Python unable to provide convenient automatic completion and other functions.
The statement about "untyped" is completely wrong. It is obviously written by someone who doesn't understand Python. Python is a "strongly typed" and "dynamically bound" language.
Slow running speed: This refers to compared with C and C++.
5 Function Introduction Edit
Python has a powerful standard library. The core of the Python language only contains common types and functions such as numbers, strings, lists, dictionaries, and files, while the Python standard library provides additional functions such as system management, network communication, text processing, database interfaces, graphics systems, and XML processing. The Python standard library has clear named interfaces and good documentation, and is very easy to learn and use.
The Python community provides a large number of third-party modules, which are used in the same way as the standard library. Their functions cover everything, covering multiple fields such as scientific computing, web development, database interfaces, and graphics systems, and most of them are mature and stable. Third-party modules can be written in Python or C language. SWIG and SIP are often used to convert C language-written program libraries into Python modules. The Boost C++ Libraries contain a set of libraries, Boost.Python, which enables programs written in Python or C++ to call each other. With the large number of tools based on the standard library, being able to use low-level languages such as C and being able to act as interfaces for other libraries, Python has become a powerful "glue language" between other languages and tools.
The main functions of the Python standard library are:
Text processing, including text formatting, regular expression matching, text difference calculation and merging, Unicode support, binary data processing, etc.
File processing, including file operations, creating temporary files, file compression and archiving, operating configuration files, etc.
Operating system functions, including thread and process support, IO multiplexing, date and time processing, calling system functions, writing logs (logging), etc.
Network communication, including network sockets, SSL encrypted communication, asynchronous network communication, etc.
Network protocols, supporting multiple network protocols such as HTTP, FTP, SMTP, POP, IMAP, NNTP, XMLRPC, and providing a framework for writing network servers.
W3C format support, including processing of HTML, SGML, XML.
Other functions, including internationalization support, mathematical operations, HASH, Tkinter, etc.
6 Design Orientation Edit
The design philosophy of Python is "elegant", "clear", and "simple". Therefore, the concept in the Perl language that "there are always multiple ways to do the same thing" is usually intolerable to Python developers. The philosophy of Python developers is "use one way, preferably only one way to do one thing". When designing the Python language, if there are multiple choices, Python developers generally refuse fancy grammars and choose clear grammars with no or few ambiguities. Due to this difference in design concepts, Python source code is usually considered to have better readability than Perl and can support large-scale software development. These guidelines are called Python maxims. Running import this in the Python interpreter can get the complete list.
Python developers try to avoid immature or unimportant optimizations. Some patches to speed up running for non-important parts are usually not merged into Python. So many people think Python is slow. However, according to the 80-20 rule, most programs do not require high speed. In some cases where high running speed is required, Python designers tend to use JIT technology, or rewrite this part of the program in C/C++ language. The available JIT technology is PyPy.
Python is a fully object-oriented language. Functions, modules, numbers, strings are all objects. And it fully supports inheritance, overloading, derivation, multiple inheritance, which is beneficial to enhancing the reusability of source code. Python supports overloading operators and dynamic typing. Compared with traditional functional programming languages such as Lisp, Python provides only limited support for functional design. There are two standard libraries (functools, itertools) that provide time-tested functional programming tools from Haskell and Standard ML.
Although Python may be roughly classified as a "script language" (script language), in fact, some large-scale software development plans such as Zope, Mnet, and BitTorrent, and Google also use it extensively. Python supporters prefer to call it a high-level dynamic programming language because "script language" generally refers to a language that only performs simple programming tasks, such as shell script, VBScript, etc., which can only handle simple tasks, and cannot be compared with Python.
Python itself is designed to be extensible. Not all features and functions are integrated into the language core. Python provides rich APIs and tools, so that programmers can easily use C language, C++, Cython to write extension modules. The Python compiler itself can also be integrated into other programs that need a scripting language. Therefore, many people also use Python as a "glue language" (glue language). Use Python to integrate and encapsulate programs written in other languages. In many projects inside Google, such as Google Engine, use C++ to write parts with extremely high performance requirements, and then use Python or Java/Go to call the corresponding modules. Alex Martelli, the author of "Python Technical Manual", said: "It's hard to say, but in 2004, Python was already used inside Google. Google recruited many Python experts, but it had already decided to use Python before that. Their purpose was Python where we can, C++ where we must, use C++ in the occasion of manipulating hardware, and use Python in the occasion of rapid development."
7 CGI Introduction Edit
CGI is currently maintained by NCSA,
CGI (Common Gateway Interface), a common gateway interface, it is a program that runs on the server such as an HTTP server and provides an interface with the client HTML page.
CGI programs can be Python scripts, Perl scripts, Shell scripts, C or C++ programs, etc.
Server
Before you do CGI programming, make sure your web server supports CGI and has configured the handler for CGI.
All HTTP servers execute CGI programs and are stored in a pre-configured directory. This directory is called the CGI directory, and by convention, it is named the /var/www/cgi-bin directory.
The extension of CGI files is.cgi, and Python can also use the.py extension.
By default, the cgi-bin directory configured to run CGI scripts on Linux servers is /var/www.
If you want to specify other directories to run CGI scripts, you can modify the httpd.conf configuration file,
1
2
3
4
5
6
7
8
9
<Directory"/var/www/cgi-bin">
AllowOverrideNone
OptionsExecCGI
Orderallow,deny
Allowfromall
</Directory>
<Directory"/var/www/cgi-bin">
OptionsAll
</Directory>
Program
Use Python to create the first CGI program, the file is named hello.py, and the file is located in the /var/www/cgi-bin directory. The content is as follows,
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/envpython
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("")
print("</head>")
print("<body>")
print("<h2>HelloWord!ThisismyfirstCGIprogram")
print("</body>")
print("</html>")
The above program displays the following result when accessed in the browser:
1
HelloWord!ThisismyfirstCGIprogram
This hello.py script is a simple Python script. The first output content "Content-type:text/html\r\n\r\n" of the script is sent to the browser and informs the browser that the content type to be displayed is "text/html".
Environment Variables
All CGI programs receive the following environment variables,
Variable Name
Description
CONTENT_TYPE
This environment variable's value indicates the MIME type of the passed information. Currently, the environment variable CONTENT_TYPE is generally: application/x-www-form-urlencoded, which means the data comes from an HTML form.
CONTENT_LENGTH
If the way the server and the CGI program pass information is POST, this environment variable is the number of valid bytes that can be read from standard input STDIN. This environment variable must be used when reading the input data.
HTTP_COOKIE Content of the COOKIE in the client machine
HTTP_USER_AGENT Provides client browser information including version number or other proprietary data
PATH_INFO
This environment variable's value indicates other path information immediately after the CGI program name. It often appears as a parameter of the CGI program.
QUERY_STRING
If the way the server and the CGI program pass information is GET, this environment variable's value is the passed information. This information follows the CGI program name and is separated by a question mark '?' between the two.
REMOTE_ADDR
This environment variable's value is the IP address of the client machine sending the request, such as the above 192.168.1.67. This value always exists. And it is the only identifier that the web client needs to provide to the web server, which can be used in the CGI program to distinguish different web clients.
REMOTE_HOST
This environment variable's value contains the hostname of the client machine sending the CGI request. If support for querying is not required, this environment variable does not need to be defined.
REQUEST_METHOD
Provides the method by which the script is called. For scripts using the HTTP/1.0 protocol, only GET and POST are meaningful.
SCRIPT_FILENAME Complete path of the CGI script
SCRIPT_NAME Name of the CGI script
SERVER_NAME This is the hostname, alias, or IP address of your WEB server
SERVER_SOFTWARE This environment variable's value contains the name and version number of the HTTP server that calls the CGI program, for example
The following is a simple CGI script to output the environment variables of CGI:
1
2
3
4
5
#!/usr/bin/pythonimportosprint"Content-type:text/html\r\n\r\n";
print"<fontsize=+1>Environment</font><\br>";
forparaminos.environ.keys():
print"<b>%20s</b>:%s<\br>"
%(param,os.environ)
8 Execution Status Edit
When Python is executed, it first compiles the source code in the.py file into Python byte code (bytecode), and then the Python Virtual Machine (Python Virtual Machine) executes these compiled bytecode. The basic idea of this mechanism is the same as that of Java and.NET. However, the Python Virtual Machine is different from the Java or.NET Virtual Machine. The Python Virtual Machine is a more advanced Virtual Machine. The advanced here does not mean powerful in the usual sense. It does not mean that the Python Virtual Machine is more powerful than the Java or.NET Virtual Machine, but that compared with Java or.NET, the Python Virtual Machine is farther from the real machine. Or it can be said that the Python Virtual Machine is a Virtual Machine with a higher level of abstraction.
The bytecode file compiled based on C Python is usually in.pyc format.
In addition, Python can also run in interactive mode. For example, mainstream operating systems such as Unix/Linux, Mac, and window can directly run the Python interactive environment in the command mode. You can directly issue operation instructions to achieve interactive operations.
9 Basic Syntax Edit
One of the design goals of Python is to make the code have high readability. When it is designed, it tries to use punctuation marks and English words often used in other languages, making the code look neat and beautiful. It does not need to repeatedly write declaration statements like other static languages such as C and Pascal, and there are no special cases and surprises in its grammar like them.
Indentation
Python developers intentionally make programs that violate the indentation rule unable to pass the compilation, so as to force programmers to develop good programming habits. And Python uses indentation to indicate the start and exit of a statement block (Off-side rule), instead of using curly braces or some keywords. Increasing indentation indicates the start of a statement block, and decreasing indentation indicates the exit of a statement block. Indentation has become part of the grammar. For example, the if statement:
Note: The above example is the code of Python 3.0 version, @ represents a space
According to the PEP regulations, 4 spaces must be used to represent each level of indentation (I don't know the regulations of 4 spaces, in actual writing, you can customize the number of spaces, but the number of spaces between each level of indentation must be equal). Using Tab characters and other numbers of spaces can all pass the compilation, but it does not conform to the coding specification. Supporting Tab characters and other numbers of spaces is only for compatibility with very old Python programs and some problematic editors.
Flow Control Statements
if statement, when the condition is true, run the statement block. Often used with else, elif (equivalent to else if) in combination.
for statement, iterate over iterators such as lists, strings, dictionaries, sets, and process each element in the iterator in turn.
while statement, when the condition is true, loop to run the statement block.
try statement. Used with except, finally in combination to handle abnormal situations that occur during program operation.
class statement. Used to define a type.
def statement. Used to define functions and methods of types.
pass statement. Indicates that this behavior is empty and no operation is run.
assert statement. Used to test whether the running condition is satisfied during the program debugging stage.
with statement. The syntax defined after Python 2.6 is to run the statement block in a scenario. For example, encrypt before running the statement block, and decrypt after the statement block runs and exits.
yield statement. Used in iterator functions to return an element. Since the Python 2.5 version. This statement has become an operator.
raise statement. Make an error.
import statement. Import a module or package.
from import statement. Import a module from a package or an object from a module.
import as statement. Assign the imported object to a variable.
in statement. Judge whether an object is in a string/list/tuple.
Expression
The expression writing of Python is similar to C/C++. Only some writing is different.
The main arithmetic operators are similar to C/C++. +, -, *, /, //, **, ~, % respectively represent addition or taking positive, subtraction or taking negative, multiplication, division, integer division, exponentiation, taking complement, taking modulus. >>, << represent right shift and left shift. &, |, ^ represent binary AND, OR, XOR operations. >, <, ==, !=, <=, >= are used to compare the values of two expressions, representing greater than, less than, equal to, not equal to, less than or equal to, greater than or equal to respectively. Among these operators, ~, |, ^, &, <<, >> must be applied to integers.
Python uses and, or, not to represent logical operations.
is, is not are used to compare whether two variables are the same object. in, not in are used to judge whether an object belongs to another object.
Python supports "list comprehension" (list comprehension), for example, calculate the sum of squares from 0 to 9:
>>> sum(x * x for x in range(10))
285
Python uses lambda to represent an anonymous function. The body of an anonymous function can only be an expression. For example:
>>> add=lambda x, y : x + y
>>> add(3,2)
5
Python uses y if cond else x to represent a conditional expression. It means that when cond is true, the value of the expression is y, otherwise the value of the expression is x. It is equivalent to cond?y:x in C++ and Java.
Python distinguishes between list (list) and tuple (tuple) types. The writing of list is , and the writing of tuple is (1,2,3). The elements in the list can be changed, but the elements in the tuple cannot be changed. In some cases, the parentheses of the tuple can be omitted. The tuple has special processing for assignment statements. Therefore, it can be assigned to multiple variables at the same time, for example:
>>> x, y=1,2#Assign values to x and y at the same time, the final result: x=1, y=2
In particular, the following form can be used to exchange the values of two variables:
>>> x, y=y, x #Final result: y=1, x=2
Python uses '(single quote) and "(double quote) to represent strings. Unlike Perl, Unix Shell language, or Ruby, Groovy and other languages, the two symbols have the same function. Generally, if double quotes appear in the string, use single quotes to represent the string; otherwise, use double quotes. If neither appears, choose according to personal preference. \ (backslash) appearing in the string is interpreted as a special character, such as \n representing a newline character. Adding r in front of the expression indicates that Python does not interpret \ appearing in the string. This writing is usually used to write regular expressions or Windows file paths.
Python supports list slicing (list slices), and can obtain a part of the complete list. Types that support slicing operations include str, bytes, list, tuple, etc. Its syntax is... or.... Assuming that the value of the nums variable is , then the following statements are true:
nums == Cut from the element with index 2 to the element with index 5, but does not include the element with index 5.
nums == Cut to the last element.
nums == Cut from the first element to the third last element.
nums == Return all elements. Changing the new list will not affect nums.
nums == Cut from the element with index 1 to the element with index 5 but does not include the element with index 5, and the step size is 2.
Function
Python's functions support recursion, default parameter values, and variable parameters, but do not support function overloading. To enhance the readability of the code, "document strings" (Documentation Strings, or简称docstrings) can be written after the function, used to explain the function's function, the type and meaning of parameters, the type and value range of the return value, etc. The built-in function help() can be used to print the usage help of the function. For example:
>>>def randint(a, b):... "Return random integer in range , including both end points."...>>>help(randint)Help on function randint in module __main__: randint(a, b) Return random integer inrange, including both end points.
Object Method
An object's method refers to a function bound to the object. The syntax for calling an object method is instance.method(arguments). It is equivalent to calling Class.method(instance, arguments). When defining an object method, you must explicitly define the first parameter. Generally, this parameter name is self, used to access the internal data of the object. Here, self is equivalent to the this variable in C++ and Java, but we can also use any other legal parameter name, such as this and mine, etc. self is not exactly the same as this in C++ and Java. It can be regarded as a habitual usage. We can pass in any other legal name, for example:
Python recognizes some special method names starting with "__" and ending with "__", which are used to implement operator overloading and implement various special functions.
Type
Python adopts a dynamic type system. At compile time, Python will not check whether an object has the called method or attribute, but will make a check until runtime. Therefore, operations on objects may throw exceptions. However, although Python adopts a dynamic type system, it is also strongly typed. Python prohibits undefined operations, such as adding a number to a string.
Like other object-oriented languages, Python allows programmers to define types. Constructing an object only needs to be called like a function, for example, for the previously defined Fish type, use Fish(). The type itself is also an object of the special type type (the type type itself is also a type object), this special design allows reflection programming on the type.
Python has rich built-in data types. Compared with Java and C++, these data types effectively reduce the length of the code. The following list briefly describes the Python built-in data types (suitable for Python 3.x):
Type
Description
Example
Remarks
str A non-changeable sequence composed of characters
'Wikipedia'
"Wikipedia"
"""Spanning
multiple
lines"""
In Python 3.x, the string is composed of Unicode characters
bytes A non-changeable sequence composed of bytes b'Some,ASCII'b",Some,ASCII"
list A changeable sequence that can contain multiple types
tuple A non-changeable sequence that can contain multiple types (4,0,'string',True)
set,frozenset Similar to the concept of a set in mathematics, unordered, each element is unique
{4.0, 'string', True}
frozenset()
dict A changeable sequence composed of key-value pairs {'key1':,1,0,3:,False}
int Integers with unlimited precision 42
float Floating-point numbers, precision related to the system 3.1415927
complex Complex numbers 3+2,7j
bool Logical values, only two values: true, false TrueFalse
In addition to various data types, the Python language also uses types to represent functions, modules, types themselves, object methods, compiled Python code, runtime information, etc. Therefore, Python has strong dynamicity.
Mathematical Operations
Python uses operators similar to C and Java to support mathematical operations of integers and floating-point numbers. It also supports complex number operations and integer operations with infinite digits (actually limited by the computer's ability). Except for the absolute value function abs(), most mathematical functions are in the math and cmath modules. The former is used for real number operations, and the latter is used for complex number operations. You need to import them first, for example:
>>>importmath>>>print(math.sin(math.pi/2))1.0
The fractions module is used to support fraction operations; the decimal module is used to support high-precision floating-point number operations.
Python defines that the value of the remainder operation a % b is in the open interval . This is a very common definition. However, it actually depends on the definition of integer division. In order for the equation: b * (a // b) + a % b = a to be true all the time, the integer division operation needs to take values in the direction of negative infinity. For example, the result of 7 // 3 is 2, while the result of (-7) // 3 is -3. This algorithm is different from many other programming languages, and needs to be noted that their integer division operations will take values in the direction of 0.
Python allows writing two comparison operations consecutively like the common writing in mathematics. For example, a < b < c is equivalent to a < b and b < c. The result of C++ is different from Python. First, it will calculate a < b, and get one of 0 or 1 according to the size of the two, and then compare with c.
10 Application Introduction Edit
System programming: Provide API (Application Programming Interface), can conveniently perform system maintenance and management, one of the iconic languages under Linux, and is an ideal programming tool for many system administrators.
Graphics processing: There are PIL, Tkinter and other graphics libraries to support, can conveniently perform graphics processing.
Mathematical processing: The NumPy extension provides a large number of interfaces with many standard mathematical libraries.
Text processing: The re module provided by Python can support regular expressions, and also provides SGML, XML analysis modules. Many programmers use Python to develop XML programs.
Database programming: Programmers can communicate with databases such as Microsoft SQL Server, Oracle, Sybase, DB2, Mysql, SQLite through modules that follow the Python DB-API (Database Application Programming Interface) specification. Python has a Gadfly module by itself, which provides a complete SQL environment.
Network programming: Provide rich module support for sockets programming, and can conveniently and quickly develop distributed application programs. Many large-scale software development plans such as Zope, Mnet, and BitTorrent. Google are using it extensively.
Web programming: The development language of the application supports the latest XML technology.
Multimedia application: Python's PyOpenGL module encapsulates the "OpenGL Application Programming Interface" and can perform 2D and 3D image processing. The PyGame module can be used to write game software.
pymo engine: PYMO is full name Python memories off, is a game engine running on Symbian S60V3, Symbian3, S60V5, Symbian3, Android systems for AVG games. Because it is developed based on the Python 2.0 platform and is suitable for creating AVG games in the style of Memories Off (memories off), it is named PYMO.
Hacker programming: Python has a hack library, which has the functions you are familiar with or not familiar with, but lacks a sense of achievement.
Write a simple crawler with Python
First, you need to obtain the corresponding HTML source code through the urllib2 module.
import urllib2
url='http://www.baidu.com/s?wd=cloga'
content=urllib2.urlopen(url).read()
With the above three sentences, the source code of the URL can be stored in the content variable, and its type is character type.
Next, you need to extract the content we need from this pile of HTML source code. Use Chrome to view the code of the corresponding content (you can also use Firebug of Firefox).
You can see that the information of the url is stored in the span tag, and regular expressions can be used to obtain the information.
Pylons-Web application framework
Zope- Application server
Plone- Content management system
Django- Web application framework that encourages rapid development
Uliweb- Lightweight Web framework developed by Chinese people
TurboGears- Another fast Web application development framework
Twisted--Python's network application framework
Python Wikipedia Robot Framework- MediaWiki's robot program
MoinMoinWiki- Wiki program written in Python
flask- Micro Web framework in Python
Webpy- Micro Web framework in Python
Bottle- Micro Web framework in Python
EVE- The online game EVE is developed a lot using Python
Reddit - Social sharing website
Dropbox - File sharing service
Pylons - Web application framework
TurboGears - Another fast Web application development framework
Fabric - A library program used to manage hundreds of thousands of Linux hosts
Trac - BUG management system written in Python
Mailman - Email list software written in Python
Mezzanine - Content management system system based on Django
Blender - Open-source 3D drawing software developed in C and Python
11 Tool Function Edit
Tkinter
Python's default graphical interface interface. Tkinter is a Python module that interfaces with Tk. The Tkinter library provides an interface to the Tk API, and it belongs to the GUI tool group of Tcl/Tk.
PyGTK
GTK+ library for Python GUI program development. GTK is the library used to implement GIMP and Gnome.
PyQt
Qt development library for Python. QT is the library that implements the KDE environment, composed of a series of modules, including qt, qtcanvas, qtgl, qtnetwork, qtsql, qttable, qtui and qtxml, containing 300 classes and more than 5750 functions and methods. PyQt also supports a module called qtext, which contains a QScintilla library. This library is the Qt interface of the Scintillar editor class.
wxPython
GUI programming framework. People who are familiar with MFC will like it very much. It is almost the same architecture (for beginners or users with low design requirements, using Boa Constructor can conveniently and quickly develop wxPython).
PIL
Python provides powerful graphic processing capabilities and provides extensive graphic file format support. This library can perform conversion, printing, and display of graphic formats. It can also perform some graphic effect processing, such as zooming, shrinking, and rotating of graphics. It is a powerful tool for Python users to process images.
Psyco
A Python code accelerator that can increase the execution speed of Python code to the level of a compiled language.
xmpppy
The XMPP protocol developed by the Jabber server. Google Talk is also an IM system using the XMPP protocol. There is an xmpppy module in Python to support this protocol. That is to say, we can communicate with the Jabber server through this module. Isn't it very cool.
PyMedia
A Python module for multimedia operations. It provides rich and simple interfaces for multimedia processing (wav, mp3, ogg, avi, divx, dvd, cdda etc). Can be used on Windows and Linux platforms.
Pmw
Python megawidgets, Python super GUI component set, a high-level GUI component built in Python using the Tkinter module. Each Pmw combines one or more Tkinter components to implement more useful and complex functions.
PyXML
A toolkit for parsing and processing XML documents in Python. The 4DOM in the package is completely compatible with the W3C DOM specification. It contains the following contents:
xmlproc: A compliant XML parser. Expat: A fast, non-validating XML parser. There are other同级别的 ones such as PyHtml PySGML.
PyGame
A module for multimedia development and game software development.
PyOpenGL
The module encapsulates the "OpenGL Application Programming Interface". Through this module, Python programmers can integrate 2D and 3D graphics in the program.
NumPy, NumArray, SAGE
NumArray is an extension library of Python, mainly used to handle fixed-type arrays of any dimension. Simply put, it is a matrix library. Its underlying code is written in C, so the speed advantage is obvious. SAGE is a mathematical software package integrated based on NumPy and several other tools. The goal is to replace tools such as Magma, Maple, Mathematica, and Matlab.
MySQLdb
Used to connect to the MySQL database. There is also the ZMySQLDA module for zope, through which you can connect to the mysql database in zope.
Sqlite3
Used to connect to the sqlite database.
Python-ldap
Provides a set of object-oriented APIs, which can conveniently access the ldap directory service in Python, and it is based on OpenLDAP2.x.
smtplib
Send emails.
ftplib
Defines the FTP class and some methods for client-side ftp programming. If you want to know the detailed content of the ftp protocol, please refer to RFC959.
12 Version Introduction Edit
The main versions of Python are 2.x and 3.x, and currently 2.x is used more. Here is an article about "whether beginners learn Python 2 or Python 3?" which is very good, you can refer to it: http://www.pythontab.com/html/2012/pythonjichu_1220/11.html
The Python 3.0 version is often called Python 3000, or abbreviated as Py3k. Compared with the early versions of Python, this is a major upgrade. In order to not bring in too much baggage, Python 3.0 did not consider backward compatibility when designing. Many programs designed for early Python versions cannot run normally on Python 3.0. In order to take into account existing programs, Python 2.6 is used as a transition version, which basically uses the syntax and library of Python 2.x, and at the same time considers the migration to Python 3.0, allowing the use of some syntax and functions of Python 3.0. Programs that can run normally on Python 2.6 without warnings based on early Python versions can be seamlessly migrated to Python 3.0 through a 2 to 3 conversion tool.
New Python programs are recommended to use the syntax of the Python 3.0 version. Unless the running environment cannot install Python 3.0 or the program itself uses third-party libraries that do not support Python 3.0. Currently, third-party libraries that do not support Python 3.0 include Django, Twisted, py2exe, PIL, etc. Most third-party libraries are working hard to be compatible with the Python 3.0 version. Even if Python 3.0 cannot be used immediately, it is recommended to write programs compatible with the Python 3.0 version, and then run them with Python 2.6, Python 2.7. Python 2.7 is determined to be the last Python 2.x version. In addition to supporting Python 2.x syntax, it also supports part of Python 3.1 syntax.
The Python 3.0 version is often called Python 3000, or abbreviated as Py3k. Compared with the early versions of Python, this is a major upgrade. In order to not bring in too much baggage, Python 3.0 did not consider backward compatibility when designing. Many programs designed for early Python versions cannot run normally on Python 3.0. In order to take into account existing programs, Python 2.6 is used as a transition version, which basically uses the syntax and library of Python 2.x, and at the same time considers the migration to Python 3.0, allowing the use of some syntax and functions of Python 3.0. Programs that can run normally on Python 2.6 without warnings based on early Python versions can be seamlessly migrated to Python 3.0 through a 2 to 3 conversion tool.
New Python programs are recommended to use the syntax of the Python 3.0 version. Unless the running environment cannot install Python 3.0 or the program itself uses third-party libraries that do not support Python 3.0. Third-party libraries that do not support Python 3.0 include Django, Twisted, py2exe, PIL, etc. Most third-party libraries are working hard to be compatible with the Python 3.0 version. Even if Python 3.0 cannot be used immediately, it is recommended to write programs compatible with the Python 3.0 version, and then run them with Python 2.6, Python 2.7. Python 2.7 is determined to be the last Python 2.x version. In addition to supporting Python 2.x syntax, it also supports part of Python 3.1 syntax.
The changes in Python 3.0 are mainly in the following aspects:
The most noticeable change is that the print statement is gone, replaced by the print() function. The 2to3 tool can be used to automatically convert print statements. Python 2.6 and Python 2.7 partially support this form of print syntax. In Python 2.6 and Python 2.7, the following three forms are equivalent:
print"fish"print("fish")#Note that there is a space after printprint("fish")#print() cannot have any other parameters
However, Python 2.6 has actually supported the new print() syntax. The method is:
from__future__import print_functionprint("fish","panda", sep=', ')
The new str type represents a Unicode string, equivalent to the unicode type in the Python 2.x version. The byte sequence is represented by a syntax like b"abc", represented by the bytes class, equivalent to the str type in the Python 2.x version. The two types can no longer be implicitly and automatically converted. Therefore, in Python 3.x, "fish"+b"panda" is wrong. The correct way is "fish"+b"panda".decode("utf-8"). Python 2.6 can automatically recognize the byte sequence as a Unicode string. The method is:
from__future__import unicode_literalsprint(repr("fish"))
The division operator / in Python 3.x always returns a floating-point number. In Python 2.6, it will judge whether the dividend and divisor are integers. If they are integers, it will return an integer value, equivalent to integer division; if they are floating-point numbers, it will return a floating-point value. In order to make Python 2.6 return a floating-point value uniformly, you can:
from__future__import divisionprint(3/2)
The syntax for catching exceptions is changed from except exc, var to except exc as var. Using the syntax except (exc1, exc2) as var can catch multiple types of exceptions at the same time. Python 2.6 has supported these two grammars.
Dictionary comprehensions (Dictionary comprehensions) {expr1: expr2 for k, v in d}, this syntax is equivalent to:
result={}for k, v in d.items(): result=expr2return result
The new writing of set (set): {1,2,3,4}. Note that {} still represents an empty dictionary (dict).
Octal numbers must be written as 0o777, and the original form 0777 is no longer available; binary must be written as 0b111. A new bin() function is added to convert an integer into a binary string. Python 2.6 has supported these two grammars.
dict.keys(), dict.values(), dict.items(), map(), filter(), range(), zip() no longer return lists, but iterators.
If there is no clearly defined and meaningful order between two objects. Comparing them with <, >, <=, >= will throw an exception. For example, 1 < "" will return True in Python 2.6, but will throw an exception in Python 3.0. The cmp(), instance.__cmp__() functions have been deleted.
The parameters and return values of the function can be annotated. This feature can facilitate IDE to perform more in-depth analysis of the source code. For example:
def sendMail(from_:"nobody@example .com", \ to:"somebody@example .com", \ title:"hello", \ body:"Just say hello to you.") ->True: pass
According to PEP8, multiple modules are renamed:
Old name
New name
_winreg winreg
ConfigParser configparser
copy_reg copyreg
Queue queue
SocketServer socketserver
repr reprlib
The StringIO module is merged into the new io module. Modules such as new, md5, gopherlib are deleted. Python 2.6 has supported the new io module.
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib are merged into the http package.
The exec statement is canceled, leaving only the exec() function. Python 2.6 has supported the exec() function.
Basically, programs that use Python 3.0 syntax and run on Python 2.6, Python 2.7 can be written.
13 Development Environment Edit
●IDLE: Python built-in IDE (provided with the python installation package)
●PyCharm: See Baidu Encyclopedia PyCharm, developed by the famous JetBrains company, with a complete set of tools that can help users improve their efficiency when developing in the Python language, such as debugging, syntax highlighting, Project management, code jumping, intelligent prompting, auto-completion, unit testing, version control. In addition, this IDE provides some advanced functions to support professional web development under the Django framework.
●Komodo and Komodo Edit: The latter is a free and streamlined version of the former
●PythonWin: Both ActivePython or pywin32 provide this IDE, only applicable to Windows
●SPE (Stani's Python Editor): A free software with more functions, based on wxPython
●Ulipad: A free software with complete functions, based on wxPython; the author is Chinese Python expert limodou
●WingIDE: Probably the most comprehensive IDE, but not free software (educational users and open-source users can apply for a free key)
●Eric: Free software based on PyQt, powerful. The full name is: The Eric Python IDE
●DrPython
●PyScripter: A lightweight open-source Python IDE developed with Delphi, supporting Python 2.6 and 3.0.
●PyPE: An open-source cross-platform Python IDE.
●bpython: A lightweight Python interpreter developed using the curses library under Unix-like operating systems. Syntax prompting function.
●eclipse + pydev plug-in: convenient for debugging programs
●emacs: has built-in Python support, and functions such as auto-completion and refactor need plug-in support
●Vim: The latest 7.3 version can be compiled with Python support when compiling, providing Python code auto-prompt support
●Visual Studio 2003 + VisualPython: only applicable to Windows, has stopped maintenance, and has poor functions
●SlickEdit
●Visual Studio 2010 + Python Tools for Visual Studio
●TextMate
●Netbeans IDE
●Sublime
In addition, general programmer text editor software such as EditPlus, UltraEdit, PSPad can also provide certain support for Python code editing, such as code automatic coloring, comment shortcuts, etc., but whether it can be regarded as an integrated development environment level is still to be evaluated.
14 Other Related Edit
Interpreter
Python is a cross-platform scripting language. Python specifies a Python grammar rule, and the interpreter that implements the Python grammar rule becomes the Python interpreter.
CPython (Classic Python, that is, the original Python implementation, which is called CPython when it needs to be distinguished from other implementations; or interpreted as a Python implemented in C language). This is the most commonly used Python version.
Jython (formerly JPython; Python implemented in Java language, which has been officially released). Jython can directly call various function libraries of Java.
PyPy (Python written in Python language)
IronPython (Python implementation for.NET and ECMA CLI). IronPython can directly call various function libraries of the.net platform. Python programs can be compiled into.net programs.
ZhPy (Zhou Python) (Python language that supports writing programs using traditional/ simplified Chinese statements)
Learning Websites
1. PythonTab Chinese Website
2. Python Enthusiasts Forum
3. Pythoner Online Interaction Platform
4. One Person One Python
References:
1.
Simple Introduction to Python
2.
Introduction to Python
3.
Whether Beginners Learn Python 2 or Python 3
Extended Reading:
1.
Introduction to Python
2.
Introduction to Python Entry
3.
Detailed Explanation of Python Tool Introduction
Entry Tags:
Programming Language, Computer, Computer, Python, Open Source
[ Last edited by zzz19760225 on 2016-9-22 at 17:35 ]
1<词>,2,3/段\,4{节},5(章)。
