Python Learning Note one: 10-minute introductory

Source: Internet
Author: User

"Turn" Why do you knock yourself? --the process of learning.

Development history

Brief introduction:

Python is a dynamically-interpreted programming language. Python can be windows,unix,mac and many more CAs


1. Python is developed using the C language, but Python no longer has complex data types such as pointers in the C language.

2. Python has very strong object-oriented features and simplifies object-oriented implementations. It eliminates object-oriented elements including types, abstract classes, interfaces, and so on.

A 3.python code block separates code by using spaces or tab indents.

4. Python has only 31 reserved words, and there are no semicolons, begin, end and other tags

5. Python is a strongly typed language, and when a variable is created, it corresponds to a data type, and variables of different types appearing in the same expression require type conversion.

Build the development environment:

1. You can download the installation package to, then install it via configure, make, made install

2. You can also go to to download the ActivePython component package. (ActivePython is a binary wrapper for the Python core and common modules, which is a Python development environment published by ActiveState Company.) ActivePython makes Python installation easier and can be applied on a variety of operating systems. ActivePython contains some common Python extensions, as well as programming interfaces for the Windows environment. For ActivePython, if you are a Windows user, download the MSI package installation, and if you are a UNIX user, download the tar.gz package and unzip it directly.

3. python IDE, including Pythonwin,eclipse+pydev plugin, Komodo,editplus (beginner's most concerned about the issue, followed by a special introduction)


Python2 and Python3 are currently the main two versions.

The following two cases are recommended for the use of Python2:

1 You cannot fully control the environment you are about to deploy;

2 You need to use some specific third-party packages or extensions;

Python3 is an officially recommended version that is fully supported in the future, and many feature enhancements are available only on the Python3 version.

Hello Word:

1. Create

if __name__ = = \'__mian__\ ':    print"Hello Word"

2. Running the program



1. Whether it is a line comment or a paragraph comment, use # plus a space to comment

2. If you need to use Chinese annotations in your code, you must precede the Python file with the following comment

1 # -*-Coding:utf-8-*-

3. The following note is used to specify the interpreter

1 # !/usr/bin/python

File type: the

1 Python's file type is divided into 3 types, 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 with a. py extension, which is interpreted by Python;

3 The source file is compiled to generate a file with a. pyc extension, which is a compiled byte file. This file cannot be modified with a text editor. The PYc file is not related to the peace platform and can be run on most operating systems. The following statements can be used to generate the PYc file:

1 Import Py_compile 2 py_compile.compile ('')

4 optimized source files are suffixed with. Pyo, which optimizes the code. It cannot be modified directly with a text editor, as the following command can be used to generate a PYO file:

1 python-o-M Py_compile


1 variables in Python do not need to be declared, and the assignment of variables is done even if the variables are declared and defined.

2 A new assignment in Python will create a new variable. Variables are identified differently, even if the names of the variables are the same. Use the ID () function to get the variable ID:

1 x = 12print  ID (x)3 x = 24print 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 and external file inside the file.

5 global variable recommendations are defined at the beginning of the file.

6 You can also put global variables into a dedicated file, and then use Import to refer to:

1 _a = 12 _b = 2

1 Import GL 2 def Fun (): 3    Print gl._a 4    Print Gl._b 5 Fun ()


There are no reserved words for defining constants in Python. You can define a constant class to implement the function of a constant.

1 class_const:2   classConsterror (TypeError):Pass3     def __setattr__(self,name,value):4         ifSelf.__dict__. Has_key (name):5            RaiseSelf. Consterror,"Can ' t rebind const (%s)"%name6Self.__dict__[name]=value7 ImportSYS8sys.modules[__name__]=_const ()

Data type:

1 Python's number types are integer, long, Float, boolean, and plural types.

2 python has no character type

3 There is no normal type inside 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 a variable or create a new type.

5 Python has 3 ways of representing string types, namely single quotes, double quotes, and three quotation marks. Single and double quotes work the same. Python programmers prefer single quotes, and C/java programmers are accustomed to using double quotes to denote strings. You can enter characters such as single quotation marks, double quotation marks, or line breaks in three quotation marks. (similar to IDL)

An operation conforms to an expression:

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

2 1/2 will be equal to 0.5 before python2.5, and will be equal to 0 after python2.5.

3 Not equal to! = or <>

4 equals = = means

5 a logical expression in which an and represents logic with, or represents a logical OR, not represents a logical non-

Control statements:

1 conditional statements:

1 if(expression):2 Statement 13 Else :4 Statement 25 6 if(expression):7 Statement 18 elif(expression):9 Statement 2Ten Else One Statement 3 A# nesting - if(expression): -   if(expression): the Statement 1 -   elif(expression): - Statement 2 -   Else + Statement 3 - elif(expression): + Statement 2 A Else atStatement 3

4 python itself does not have a switch statement.

5 Loop statement:

 while (expression):  ... Else  :  ...  for inch collection:   ... Else  :  ...

7 Python does not support loop statements like C for (i=0;i<5;i++), but can be simulated with the range :

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


1 tuples (tuple): A built-in data structure in Python. tuples consist of different elements , each of which 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, and elements in tuples represent different data items. Tuples can be considered as non-modifiable arrays. Examples of creating tuples are as follows:

Tuple_name= ("Apple","banana","Orange ")

2 lists [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 . A list is an array in the traditional sense. The list creation example is as follows:

List = ["grage","Orange"]

You can use the Append method to append an element at the tail, and remove to delete the element.

3 Dictionary {Dictionary}: A collection of key-value pairs that are referenced by a key in the dictionary. The keys and values are separated by colons, and the key-value pairs are separated by commas and are enclosed in a pair of curly braces. The following examples are created:

dict={"a":"Apple","b" :"banana"}

4 sequence: A sequence is a collection with the ability to index and slice. Tuples, lists, and strings belong to a sequence.


1 Python programs consist of packages, modules, and functions . A package is a collection of modules that are made up of a series. A module is a collection of functions and classes that handle a class of problems.

The 2 package is a toolbox that accomplishes a specific task.

3 package must contain a that identifies the current folder as a package.

The 4 Python program is made up of modules. A module organizes a set of related functions or code into a file, and a file is a module . Modules consist of code, functions, and classes. Import module uses import phrases.

The function of 5 package is to realize the reuse of the program.

The 6 function is a code that can be repeated several times, and the function definition example is as follows:

1 defarithmetic (x,y,operator):2Resul={3           "+": x+y,4           "-": X-y,5           "*": x*y,6           "/": x/y,7}

7 function return value can be controlled by return.


1 Formatted output:

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

2 Merging strings with +:

1 strl1="hello"2 str2="World"3 Result=str1+str2

3 The string intercept can be indexed/sliced or through the split function.

4 truncate a string by slicing:

1 word="World"2print Word[0:3]

5 Python uses = = and! = To perform string comparisons. If the two variables of the comparison are of different types, the result must be

File processing:

1 Simple processing files:

1 context="hello,world"2 f=file ("hello.txt" ,'w')3f.write (context)4 f.close

2 Read the file you can use the ReadLine () function, the ReadLines () function, and the Read function.

3 Write files can use the Write (), Writelines () function

Objects and classes:

1 Python defines a class with class reserved words, with the first character of the class name capitalized . When a programmer needs to create a type that cannot be represented by a simple type, it is necessary to define the class and then create the object with the defined class. To define a class example:

1 class Fruit: 2     def   Grow (self):3          Print " Fruit Grow "

2 When an object is created, it contains three aspects, the handle, the property, and the method of the object. Methods for creating objects:

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

3 Python does not have a protection type modifier

The 4-class approach is also divided into public and private methods. A private function cannot be called by a function other than this class, and a private method cannot be called by an external class or function.

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 is named __init__, and the destructor is named __del__

7 How to use inheritance:

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

To connect to MySQL:

1 using the MYSQLDB module to operate the MySQL database is very convenient. The sample code is as follows:

1 ImportOS, sys2 ImportMySQLdb3 Try:4Conn MySQLdb.connect (host='Locathost', user='Root', passwd= ', db=' address ')5 exceptexception,e:6     Printe7 sys.exit ()8Cursor=conn.cursor ()9Sql= ' INSERT into address (name, address) values (%s,%s) 'TenValue=(" Zhangsan", "Haidian"), ("Lisi", "Haidian")) One Try A Cursor.executemany (sql,values) - exceptException, E: -     Printe theSql= "SELECT * fromAddress " - cursor.execute (SQL) -Data=Cursor.fetchall () - ifData +      forXinchData: -         PrintX[0],x[1] + cursor.close () AConn.close ()

Python Learning Note one: 10-minute introductory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.