Simple 10-minute Python starter tutorial

Source: Internet
Author: User
Tags print format

Python is a dynamically-interpreted programming language. Python can be used on a variety of operating systems, such as Windows, UNIX, and Mac, or in Java,. NET development platform.


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 such as protection types, abstract classes, interfaces, and so on.

3 python code blocks delimit code by using spaces or tab indents.

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

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 a uniform expression require type conversion.

"Building a development environment"

1 You can download the installation package to and 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 plug-ins, Komodo, EditPlus


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 World"

1 Creating

2 Writing the program:

if __name__ = = \ ' __main__\ ':  print "Hello word"

3 Running the program:



1 both the line comment and the paragraph comment are annotated with # and a space.

2 If you need to use Chinese annotations in your code, you must include the following comment at the top of the Python file:


3 The following note is used to specify the interpreter

#! /usr/bin/python

"File Type"

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:

Import py_compilepy_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:

Python-o-M Py_complie


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:

x = 1print ID (x) x = 2print 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:

The contents of the file are as follows:

_a = 1_b = 2

Referencing global variables in

Import Gldef Fun (): Print gl._a print gl._bfun ()


There are no reserved words for defining constants in Python. You can define a constant class to implement the function 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]=valueimport syssys.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.

"Operators and Expressions"

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 Statement"

1 conditional statements:

if (expression):  statement 1else:  statement 2

2 conditional statements:

if (expression): statement 1elif (expression): statement 2...elif (expression): statement nelse: statement m

3 Conditional nesting:

if (expression 1): if (expression 2):  statement 1 elif (expression 3): Statement  2 ... else:  statement 3elif (expression N):  ... else:  .

4 python itself does not have a switch statement.

5 Loop statement:

while (expression):  ... else: ...  

6 Loop statement:

For variable in collection:  ... else: ...  

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

For x in range (0,5,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", "grape", "orange")

2 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=["Apple", "banana", "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", "G": "Grage", "O": "Orange"}

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

"Function related"

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 file 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. The import module uses the import statement.

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:

def arithmetic (x,y,operator):  result={   "+": X+y,   "-": X-y,   "*": X*y,   "/": X/Y  }

7 function return value can be controlled by return.


1 Formatted output:

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

2 Merging strings with +:

str1= "Hello" str2= "World" result=str1+str2

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

4 truncate a string by slicing:

Word= "World" print Word[0:3]

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

"File Processing"

1 Simple processing files:

context= "Hello,world" F=file ("Hello.txt", ' W ') f.write (context); 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:

Class Fruit:
def grow (self):
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:

Fruit = fruit () 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:

Class Apple (Fruit):  def ...

"Connect to MySQL"

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

Import OS, sysimport mysqldbtry:  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 esql= "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!

  • 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.