Python language ten minutes Quick Start

Python (python) is a dynamic interpreted programming language. Python can be used on Windows, UNIX, MAC and other operating systems can also be used on Java, .NET development platform.

AD:
[Sharon] 51CTO era of mobile technology for data mining and behavioral analysis - allows user data more exciting!

 

[Introduction]

Python (python) is a dynamic interpreted programming language. Python can be used on Windows, UNIX, MAC and other operating systems can also be used on Java, .NET development platform.

python logo

python logo

 

[Features]

Python using C language. 1, but no more complex Python data type in C language pointer or the like.

2 Python has a strong object-oriented features, and simplifies the object-oriented implementation. It eliminates the element type of protection, an abstract class, object-oriented interface.

3 Python code block with a space or tab codes separated by indented manner.

4 Python only 31 reserved words, and no semicolon, begin, end the like numerals.

5 Python is a strongly typed language, will create the variable corresponding to a data type, there are different types of variables in a unified expression of the need to do type conversion.

python_book

python book

[Setup the development environment]

1 www.python.org to download the installation package can then be installed by configure, make, make install.

2 can also be downloaded to the www.activestate.com ActivePython package assembly. (ActivePython is a binary package for Python and common core module, which is released by ActiveState Python Python development environment .ActivePython makes installation easier and can be applied to a variety of operating systems .ActivePython contains some common Python extensions, and the Windows environment programming interface). For ActivePython, if you are a windows user, download msi package can be installed; if you are a Unix user, download the tar.gz package directly extracted.

3 Python the IDE, including PythonWin, Eclipse + PyDev plug, Komodo, EditPlus

【version】

python2 and python3 is currently the main two versions.

Under the following two conditions are recommended python2:

1 You can not completely control the environment when you are about to deploy;

2 you need to use certain third-party packages or extend the time;

python3 is the official recommended and the full support of the future version, currently only enhance the many features on python3 version.

【hello world】

1 Create hello.py

2 programming:

  1. if __name__ == '__main__':
  2. print "hello word"

3 run the program:

  1. python ./hello.py

Explanatory Note

1 Whether or segment comment line comment, # are a space to comment.

2 If you need to use the Chinese comments in the code, you must add the following explanatory notes in front python file:

  1. # -* - coding: UTF-8 -* -

Note 3 below specifies the interpreter

  1. #! /usr/bin/python

【file type】

1 Python be divided into three types of files, i.e., source code, bytecode, and optimized code. These can be run directly, you do not need to be compiled or connection.

2 .py source code extension, be responsible for the interpretation by the python;

3 after the source file extension .pyc compiled to generate a file, the file that is compiled byte. Such files can not use a text editor to modify. pyc files are platform-independent and can run on most operating systems. The following statement can be used to generate pyc file:

  1. import py_compile
  2. py_compile.compile(‘hello.py’)

4 optimized source file will .pyo suffix, namely optimized code. It can not be modified directly with a text editor, the following command can be used to generate pyo file:

  1. python -O -m py_complie hello.py

【variable】

1 python variables need not be declared even if the process variable declaration and definition of the variable assignment.

2 python in a new assignment, will create a new variable. Even if the variable of the same name, identification variable is not the same. By id () function can fetch identifier:

  1. x = 1
  2. print id(x)
  3. x = 2
  4. print id(x)

3 If the variable is not assigned, the python considered the variable does not exist

4 variables defined outside the function can be referred to as a global variable. Global variables can be accessed by any function of internal and external document file.

5 recommended to define global variables at the beginning of the file.

6 can also put the global variables into a special file, and then referenced by import:

gl.py file reads as follows:

  1. _a = 1
  2. _b = 2

use_global.py referenced global variables:

  1. import gl
  2. def fun():
  3. print gl._a
  4. print gl._b
  5. fun()

【constant】

python does not provide a definition of the constants of reserved words. You can define your own categories to achieve a constant constant function.

  1. class _const:
  2. class ConstError(TypeError): pass
  3. def __setattr__(self,name,vlaue):
  4. if self.__dict__.has_key(name):
  5. raise self.ConstError, “Can’t rebind const(%s)”%name
  6. self.__dict__[name]=value
  7. import sys
  8. sys.modules[__name__]=_const()

【type of data】

1 python numeric types are divided into integer, long integer, float, boolean, complex types.

2 python no character type

Internal 3 python no ordinary type, any type is an object.

4 If you need to see the type of a variable, you can use type class that can return type of a variable or create a new type.

5 python There are three types of string representing a way that the single and double quotation marks, three marks. Acting Single and double quotes are the same. python programmers prefer to use single quotes, C / Java programmers are accustomed to using double quotation marks string. Three single quotes may enter double quotation marks, or the like newline characters.

Operator [] and expression

1 python operator does not support the increment and decrement operator. For example, i ++ / i- is wrong, but i + = 1 is possible.

2 1/2 before python2.5 be equal to 0.5, after python2.5 be equal to zero.

3 is not equal to! = Or <>

4 is represented by equal ==

5 logical expression and presentation logic, or logic represents or, not logical negation

[Control] Statement

1 conditional statement:

  1. if (expression):
  2. Statement 1
  3. else :
  4. Statement 2

2 conditional statement:

  1. if (expression):
  2. Statement 1
  3. elif (expression):
  4. Statement 2
  5. elif (expression):
  6. Statement n
  7. else :
  8. Statement m

3 nested conditions:

  1. if (Expression 1):
  2. if (Expression 2):
  3. Statement 1
  4. elif (Expression 3):
  5. Statement 2
  6. else:
  7. Statement 3
  8. elif (expression n):
  9. else :

4 python itself does not switch statement.

5 loop:

  1. while (expression):
  2. else :

6 loop:

  1. for variables in the set:
  2. else :

7 python c, does not support similar for (i = 0; i <5; i ++) such a loop, but the range can be simulated by means of:

  1. for x in range(0,5,2):
  2. print x

[] An array of related

1 yuan group (tuple): python a built-in data structures. Tuples of different elements, each element may store different types of data, such as strings, numbers and even elements. Tuple is write protected, that can not be modified after a tuple is created. Often represents a row of data tuples, and a tuple of elements represent different data items. Tuples can be seen as an array of non-modifiable. Creating a tuple examples are as follows:

  1. tuple_name=(“apple”,”banana”,”grape”,”orange”)

2 list (list): Similar lists and tuples, but also by a set of elements, the list may be implemented to add, delete, and lookup operations, the value of the element can be modified. The list is an array of traditional sense. Create a list of examples:

  1. list=[“apple”,”banana”,”grage”,”orange”]

You can use the append method to append elements to the end, using remove to remove elements.

3 dictionary (dictionary): from the key - a set of pairs of values, the value of the dictionary referenced by the key. Between the key and value separated by a colon, the key - value pairs separated by a comma, and is contained in a pair of curly brackets. Create a sample as follows:

  1. dict={“a”:”apple”, “b”:”banana”, “g”:”grage”, “o”:”orange”}

Sequence 4: is a collection of sequences having the ability to index and slice. Tuples, and strings belong sequence listing.

[Function] related

1 python a program package (package), the module (Module1), and functions. Package is a collection of a series of modules. Module is a collection of functions and classes of a class of processing problems.

2 package is a toolbox complete a specific task.

3 package must contain a __init__.py file, which is used to identify the current folder is a package.

4 python is a program module thereof. Module of a group of related functions or code organized into a file, a file that is a module. By the code module, functions and classes. Import module using the import statement.

5 effect achieved is to reuse the package program.

6 is a function of code that can be repeated call, example function is defined as follows:

  1. def arithmetic(x,y,operator):
  2. result={
  3. "+": X + y,
  4. "-": xy,
  5. "*": X * y,
  6. "/": X / y
  7. }

7 return function return values ​​can be controlled.

[String] related

Output Format 1:

  1. format=”%s%d” % (str1,num)
  2. print format

2 + merge with the string:

  1. str1=”hello”
  2. str2=”world”
  3. result=str1+str2

3 taken through the string index / slice, can also split function.

4 taken by slicing string:

  1. word=”world”
  2. print word[0:3]

5 python using == and! = String comparison is performed. If two variables of the type of comparison is not the same, then the result will be different.

[File]

1 simple processing file:

  1. context=”hello,world”
  2. f=file(“hello.txt”,’w’)
  3. f.write(context);
  4. f.close()

2 may be used to read the file the readline () function, readlines () function and the read function.

3 may be used to write a file write (), writelines () function

[] Objects and classes

1 python reserved word to define a class by class, the class name of the first character to be capitalized. When the type of programmer to be created can not be represented by simple type, we need to define the class and using the defined classes to create objects. Defined class example:

  1. class Fruit:
  2. def grow(self):
  3. print “Fruit grow”

After 2 when an object is created, comprising three characteristics, i.e. the handle, the object properties and methods. Create object:

  1. fruit = Fruit()
  2. fruit.grow()

3 python unprotected types of modifiers

The method is also divided into four categories public methods and private methods. Private function can not be outside the class function call, the method can not be outside the private class or function calls.

Method 5 python using the function "staticmethod ()" or "@ staticmethod" instructions function to convert a normal static method. Static method is equivalent to global function.

6 python constructor called __init__, destructor called __del__

7 inheritance to use:

  1. class Apple(Fruit):
  2. def …

[Connection] mysql

1 MySQL database very easy to use MySQLdb module operation. Sample code is as follows:

  1. import os, sys
  2. import MySQLdb
  3. try:
  4. conn MySQLdb.connect(host=’localhost’,user=’root’,passwd=’’,db=’address’
  5. except Exception,e:
  6. print e
  7. sys.exit()
  8. cursor=conn.cursor()
  9. sql=’insert into address(name, address) values(%s, %s)’
  10. value = (( "zhangsan", "haidian"), ( "lisi", "haidian"))
  11. try
  12. cursor.executemany(sql,values)
  13. except Exception, e:
  14. print e
  15. sql=”select * from address”
  16. cursor.execute(sql)
  17. data=cursor.fetchall()
  18. if data
  19. for x in data:
  20. print x[0],x[1]
  21. cursor.close()
  22. conn.close()

Reproduced in: https: //www.cnblogs.com/sinbad-li/p/5072955.html

Guess you like

Origin blog.csdn.net/weixin_33896069/article/details/93407964