Introduction
Python is a dynamically interpreted programming language. Python can be used on a variety of operating systems such as Windows, UNIX, Macs, or in Java,. NET development platform.
Characteristics
1 Python is developed using the C language, but Python no longer has complex data types such as pointers in C.
2 Python has a strong object-oriented character and simplifies object-oriented implementations. It eliminates object-oriented elements such as protection types, abstract classes, interfaces, and so on.
3 The Python code block separates the code using Spaces or tab indents.
4 Python has only 31 reserved words and no sign of semicolons, begin, end, and so on.
5 Python is a strongly typed language, and variables are created to correspond to a data type, and different types of variables appearing in the unified expression need to be cast.
"Build the development environment"
1 You can download the installation package to www.python.org and then install it via configure, make, made install.
2 You can also go to www.activestate.com to download the ActivePython component package. (ActivePython is a binary wrapper over the Python core and common modules, which is the Python development environment released by the ActiveState Company.) ActivePython makes Python installation easier and can be applied to a variety of operating systems. ActivePython contains some common Python extensions, as well as programming interfaces for Windows environments. For ActivePython, if you are a Windows user, download the MSI package installation; If you are a UNIX user, download the tar.gz package and unzip it directly.
3 Python IDE, including Pythonwin, Eclipse+pydev plug-ins, Komodo, EditPlus
Version
Python2 and Python3 are currently the main two versions.
Python2 is recommended for use in the following two cases:
1 You cannot fully control the environment you are about to deploy;
2 You need to use some specific third-party packages or extensions when;
Python3 is an officially recommended and fully supported version of the future, and many features are currently being upgraded only on the Python3 version.
"Hello World"
1 Creating hello.py
2 Writing Program:
if __name__ = = \ ' __main__\ ':
print "Hello word"
3 Running the program:
Comments
1 Whether it is a line comment or a paragraph comment, it is annotated with a # plus a space.
2 If you need to use the Chinese annotation in your code, you must precede the Python file with the following note:
3 The following annotation is used to specify the interpreter
"File Type"
1 python file types are divided into 3 categories, namely source code, byte code, and optimized code. These can be run directly and do not need to be compiled or connected.
2 source code is extended with. PY, which is explained by Python;
3 source files are compiled to generate a. pyc file with a compiled byte file. This file cannot be modified using a text editor. PYC files are not platform-independent and can be run on most operating systems. The following statements can be used to produce PYC files:
Import py_compile
py_compile.compile (' hello.py ')
4 optimized source files will have the. pyo as the suffix, that is, optimize the code. Nor can it be modified directly with a text editor, as the following command can be used to generate PYO files:
Python-o-M Py_complie hello.py
Variable
1 The variables in Python do not need to be declared, and the assignment of variables is manipulated even though the variable is declared and defined by the procedure.
2 A new assignment in Python creates a new variable. A variable's identity is not the same, even if the variable has the same name. Use the ID () function to get the variable ID:
x = 1
Print ID (x)
x = 2
Print ID (x)
3 If the variable is not assigned, Python thinks the variable does not exist
4 variables defined outside a function can be called global variables. Global variables can be accessed by any function and external file inside the file.
5 Global variables are recommended at the beginning of a file.
6 You can also place the global variable in a specialized file and then refer to it by import:
The contents of the gl.py file are as follows:
Global variables are referenced in use_global.py:
Import GL
def fun ():
print gl._a
print gl._b
fun ()
constant
There are no reserved words in Python that define constants. You can define a constant class to implement the functionality of a constant.
Class _const:
class Consterror (typeerror): Pass
def __setattr__ (Self,name,vlaue):
if self.__dict__. Has_key (name):
raise self. Consterror, "Can ' t rebind const (%s)"%name
self.__dict__[name]=value
import sys
sys.modules[__name__ ]=_const ()
"Data Type"
1 Python's numeric types are integral, long, floating-point, boolean, and plural.
2 python has no character type
3 There is no normal type within Python, and any type is an object.
4 If you need to see the type of a variable, you can use the type class, which can return the type of the variable or create a new one.
5 Python has 3 ways of representing string types, single quotes, double quotes, and triple quotes. Single and double quotes have the same effect. Python programmers prefer to use single quotes, C/java programmers are accustomed to using double quotes to denote strings. In three quotes, you can enter characters such as single quotes, double quotes, or newline.
"Operators and Expressions"
1 Python does not support both the self-add operator and the self-subtraction operator. For example i++/i-is wrong, but I+=1 is OK.
2 1/2 will be equal to 0.5 before python2.5, and will be equal to 0 after python2.5.
3 is not equal to!= or <>
4 equals = =
5 logical expressions and represents logic and, or, or, not a logical
"Control Statement"
1 Conditional statement:
if (expression):
statement 1
else:
statement 2
2 Conditional statement:
if (expression):
statement 1
elif (expression):
statement 2
...
elif (expression):
statement n
else:
statement m
3 Condition Nesting:
if (expression 1):
if (expression 2):
statement 1
elif (expression 3):
statement 2
...
ELSE:
Statement 3
elif (expression N):
...
else: ...
4 python itself does not have a switch statement.
5 Circular Statements:
while (expression): ...
else: ...
6 Circular Statements:
For variable in collection:
...
else: ...
7 Python does not support circular statements such as C for (i=0;i<5;i++), but it can be simulated by using range:
For x in range (0,5,2):
print X
"Array-related"
1-tuple (tuple): a built-in data structure in Python. Tuples consist of different elements, and each element can store different types of data, such as strings, numbers, or even elements. Tuples are write-protected, meaning that tuples cannot be modified after they are created. Tuples tend to represent a row of data, whereas elements in a tuple represent different data items. You can think of tuples as an array that cannot be modified. Examples of creating tuples are as follows:
Tuple_name= ("Apple", "banana", "grape", "orange")
2 list (list): Lists and tuples are similar and consist of a set of elements that can be added, deleted, and found, and the values of the elements can be modified. Lists are arrays in the traditional sense. List creation examples are as follows:
list=["Apple", "banana", "grage", "Orange"
You can use the Append method to append elements to the tail and remove the elements using remove.
3 Dictionary (Dictionary): A set of key-value pairs in which the values in a dictionary are referenced by a key. Keys and values are separated by colons, and key-value pairs are separated by commas and are included in a pair of curly braces. Create an example as follows:
Dict={"A": "Apple", "B": "Banana", "G": "Grage", "O": "Orange"}
4 sequence: A sequence is a collection of indexes and slicing capabilities. Tuples, lists, and strings are part of a sequence.
"Function related"
1 Python programs consist of packages (package), modules (module), and functions. A package is a collection of modules that are composed of a series. A module is a collection of functions and classes that handle a particular type of problem.
The 2 package is a toolbox that completes a specific task.
The 3 package must contain a __init__.py file that identifies the current folder as a package.
4 python programs are made up of modules. A module organizes a set of related functions or code into a file, a file that is a module. Modules consist of code, functions, and classes. The import module uses the import statement.
The function of 5 packets is to realize the reuse of the program.
The 6 function is a code that can be repeated multiple times, and the function definition example is as follows:
def arithmetic (x,y,operator):
result={
"+": X+y,
"-": X-y,
"*": X*y,
"/": x/y
}
7 function return value can be controlled by returns.
"String-related"
1 Formatted output:
format= "%s%d"% (str1,num)
print format
2 Merging strings with +:
str1= "Hello"
str2= "World"
result=str1+str2
3 string captures can be either indexed/sliced or split functions.
4 intercepting strings by slicing:
Word= "World"
print Word[0:3]
5 Python uses = = and!= for string comparisons. If the two variables of the comparison are of different types, the result is necessarily the same.
"File Handling"
1 Simple processing files:
context= "Hello,world"
f=file ("Hello.txt", "W")
f.write (context);
F.close ()
2 read files can use the ReadLine () function, the ReadLines () function, and the Read function.
3 Write file can use the Write (), Writelines () function
"Objects and Classes"
1 Python uses class reserved words to define a class, with the first character of the class name to be capitalized. When a programmer needs to create a type that cannot be represented by a simple type, you need to define the class and then create the object with the defined class. To define a class example:
Class Fruit:
def grow (self):
Print "Fruit Grow"
2 When an object is created, it contains three attributes, the object's handle, its properties, and its methods. How to create an object:
Fruit = fruit ()
fruit.grow ()
3 Python does not have a protected type modifier
The 4 class methods are also divided into public and private methods. Private functions cannot be called by functions outside of the class, and private methods cannot be called by external classes or functions.
5 Python uses the function "Staticmethod ()" or "@ Staticmethod" instructions to convert a normal function to a static method. A static method is equivalent to a global function.
6 Python's constructor name is __init__, and the destructor is named __del__
7 How to use inheritance:
Class Apple (Fruit):
def ...
"Connect MySQL"
1 using the MYSQLDB module to operate the MySQL database is very convenient. The sample code is as follows:
Import OS, sys
import mysqldb
try:
conn mysqldb.connect (host= ' localhost ', user= ' root ', passwd= ', db= ') Address '
except exception,e:
print e
sys.exit ()
cursor=conn.cursor ()
sql= ' insert INTO Address (name, address) values (%s,%s) '
value= (("Zhangsan", "Haidian"), ("Lisi", "Haidian"))
try
Cursor.executemany (sql,values)
except Exception, E:
print e
sql= "SELECT * From Address"
Cursor.execute (SQL)
Data=cursor.fetchall ()
if data for
x in data:
print x[0],x[1]
Cursor.close ()
conn.close ()
Thank you!