Note: If you have C + + base, 30 minutes to learn Python
1. Comment 2, whether it is a line comment or a paragraph comment, by using the # Plus a space. If you need to use Chinese comments in your code, you must precede the Python file with the following comment #-*-Coding:uif-8-* 3. The following comment is used to specify interpreter #. /usr/bin/python a shell-like #!/bin/bash file type the file type of Python is divided into 3 types, namely source code, byte code, and optimized code. These can be run directly, do not need to compile or link 2. The source code is extended with. PY, which is interpreted by Python to generate an extension. pyc file, that is, a compiled byte file. This file cannot be modified using a text editor. PYC is platform independent and can be run by Linux and Windows. The following statement is used to compile the import py_compile py_compile.compile (' hello.py ') 4. The optimized source file will have a. pyo suffix, that is, optimize the code. It cannot be modified by a text editor, as the following command is used to produce pyo files python-0-m py_complie hello.py variable 1Python variables do not need to be declared, and the assignment of a variable is a new assignment in the process 2.Python of a variable declaration and definition, A new variable is created. A variable's identity is not the same, even if the variable has the same name. The ID () function can be used to obtain a variable identity such as: x = 1 Print ID (x) x = 2 print ID (x) 3. If the variable is not assigned, Python does not think the variable exists 4. A variable defined outside a function can be called a global variable. Global variables can be accessed by any function within the file and by external files 5 global variables recommended at the beginning of the file, the definition of 6 can also put the global variables in a special file, and then use Import to refer to the contents of such as gl.py as follows _a = 1-b = 2 use_global.py Reference Global Change Volume: Import GL def fun (): print gl._a print gl._b fun () constant there is no reserved word in Python that defines a constant. You can define a constant class to implement a constant function class _const: class Consterror (TypeError): Pass &NBSP ; def _setattr_ (Self,name,value): if Self._dict_.has_key (name): &NB Sp raise self. Consterror, "Can ' t rebind const (%s)"%name Self._dict_[name]=value Import sys s Ys.modules[_name_]=_const () data type 1 Python's numeric types are integral, long, floating-point, Boolean, complex, 2 python, no character type 3 python has no normal type inside, and any type is 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 type 5 Python has 3 ways of representing string types, namely single quotes, double quotes, and triple quotes. Single and double quotes have the same effect. Python programmers prefer to use single quotes, and C/java is accustomed to using double quotes to denote strings. Triple quotes can enter characters such as single quotes, double quotes, or newline. operator and expression 1 Python does not support the self-add operator and the self-subtraction operator. For example i++/i--is wrong, single i+=1 can be 2. 1/2 equals 0.5,python2.5 before Python2.5 equals 0 3. Not equal to. = or <> 4 equals = 5 logical expression and representation 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 Conditional nesting: if (expression 1): if (expression 2): Statement 2 ... else: Statement 3 elif (expression N): & nbsp ... else: ..... 4Python No switch statement 5 loop statement while (expression): ... else: ... 6 Loop statement for variable in collection: ... else: .... 7Python does not support circular statements such as for (i=0;i<5;i++) in C, but can be used in the range simulation for x in range (0,5,2): print x array Related: 1 tuples: A built-in number in Python According to the structure. 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. Create an instance as follows: Tuple_name= ("Apple", "banana", "grape", "orange") 2 list (list): Lists and tuples are similar, there is 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. The list is created as follows: list=["Apple", "Banaa", "Grape", "orange" You can use the Append method to append elements to the tail, and remove elements using the Remove. 3 Dictionary (Dictionary): A value in a collection dictionary consisting of a key-value pair that is referenced by a key. Keys and values are separated by colons, separated by a comma between key-value pairs, and are enclosed in a pair of curly braces. Ono Create an example as follows: Dict={"a": "Apple", "B": "Banana", "G": "Grape", "O": "Orange"} 4 sequence: A sequence is a collection that has the ability to index and slice. Tuples, lists, and dictionaries all belong to a sequence. Function-related 1 Python programs consist of packages, modules, and functions. A package is a collection of modules that are composed of a series. A collection of functions and classes that handle a class of problems in a modular way 2 packages is a toolbox that completes a particular 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 are made up of code, functions, and classes. The import module uses the IMPORT statement 5 package to implement the program's Reuse 6 function is a code that repeats multiple calls, and the function example is as follows: Def arithmetic (x, y,operator): result={ "+": x+y, "-": XY, "*": x*y, "/": x/y,} 7 function return value can be used to control string-related formatted output: format= "% s%d "% (str1,num) print format 2 combined with + for strings str1 =" Hello "str2 =" World "Result=str1 + str2 3 string interception can be indexed/sliced or can survive spli T function 4 intercepts strings by slicing: Word = "World" print Word[0:3] 5 python uses = = and. = To make a string comparison. If the comparison of the two variable types is not the same, then the result must be different file processing simple processing file: context= "Hello,word" F=file ("Hello.txt", "W") F.write (context): F.close () 2 Read the file you can use the ReadLine () function readlines () function and the Read function 3. write file can use write (), Writelines () function objects, and Class 1 Python define a class with dass reserved words, and the first character of the class name is larger. The type that the file programmer needs to create is not a simple type to represent, you need to define the class, and then use the defined class to create the object. Defining class Instances: class Fruit: def grow (self): print "Fruit grow" 2 when an object is created, it contains three aspects of the attribute, that is, the object Handle properties and methods for creating objects: Fruit = fruit () fruit.grow () 3 Python methods that do not have a protected type of modifier 4 are also divided into public and private methods. Private functions cannot be called by functions other than this class, and private methods cannot be called by external classes or functions 5 Python uses the function "Staticmethod ()" or "@ Staticmethod" instructions to convert ordinary functions to static methods. A static method is equivalent to a global function. The 6Python constructor is a _int_. Destructor is a method of _del_ 7 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: Strong>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 ()
|