This article is a brief introduction to Python in ten minutes. The simplicity of The Python language itself has made Python shutter tutorials very popular on the Internet. This article is one of the most popular Python shutter tutorials in China
【 abstract 】
Python is a dynamically interpreted programming language. Python is available on various operating systems, including Windows, UNIX, and MAC, as well as Java and.NET development platforms.
【 characteristics 】
Python is developed in C, but Python no longer has complex data types such as Pointers in C.
Python has strong object-oriented features and simplifies object-oriented implementation. It eliminates object-oriented elements such as protected types, abstract classes, interfaces, etc.
3 Python code blocks are separated by Spaces or TAB indents.
4 Python has only 31 reserved words and no semicolon, begin, or end tags.
Python is a strongly typed language. Variables are created to correspond to one data type. Variables of different types that appear in a uniform expression need to be cast.
[Setting up the development environment]
1 You can download the installation package at www.python.org, and then install it by running configure, make, and make install.
2 You can also download the ActivePython component package at www.activestate.com. ActivePython is a binary wrapper around Python’s core and commonly used modules. It is a Python development environment published by ActiveState Corporation. ActivePython makes Python easier to install and can be used on a variety of operating systems. ActivePython includes several common Python extensions, as well as programming interfaces for Windows environments. For ActivePython, if you are a Windows user, download the MSI package and install it. If you are a Unix user, download the tar.gz package and decompress it.
3 Python IDE, including PythonWin, Eclipse+PyDev plug-in, Komodo, EditPlus
“Version”
Python2 and PYTHon3 are the two main versions available today.
Python2 is recommended in the following two cases:
1 when you don’t have full control over the environment you are deploying to;
When you need to use some specific third-party package or extension;
Python3 is officially recommended and fully supported in the future, and many of the enhancements are currently only in Python3.
From basic Python scripting to Web development, crawler, data analysis, data visualization, machine learning, and more. Those who want these materials can pay attention to xiaobian, and make small letters in the background
“Hello world”
1 create hello. Py
2. Programming:
if __name__ == \'__main__\':
print "hello word"
Copy the code
3 Run the program:
python ./hello.py
Copy the code
【 notes 】
Either line or paragraph comments are commented with # and a space.
2 if you want to use Chinese comments in your code, you must add the following comment at the beginning of the Python file:
-* – coding: UTF-8 -* –
3 The following comments are used to specify the interpreter
#! /usr/bin/python
[File type]
Python has three file types: source code, bytecode, and optimized code. These can be run directly without compilation or concatenation.
2 source code with.py extension is interpreted by Python.
3 Source files are compiled to generate files with the. Pyc extension, that is, compiled byte files. This file cannot be modified using a text editor. Pyc files are platform independent and run on most operating systems. The following statements can be used to generate pyC files:
Import py_compile py_compile.compile(‘ hello.py’) 4 Optimized source files will have a. Pyo suffix, i.e. optimized code. It also cannot be modified directly with a text editor. The following command can be used to generate pyo files:
python -O -m py_complie hello.py
“Variable”
1 Variables in Python do not need to be declared, and the assignment of a variable is a process of variable declaration and definition.
A new assignment in Python creates a new variable. Even if the names of variables are the same, the identities of variables are not. 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 does not consider it to exist
Any variable defined outside a function can be called a global variable. Global variables can be accessed by any function inside the file and by external files.
5 You are advised to define global variables at the beginning of the file.
6 You can also import global variables into a special file:
The gl.py file contains the following contents:
From basic Python scripting to Web development, crawlers, data analysis, data visualization, machine learning, and more. Those who want these materials can pay attention to xiaobian and get “07” in the background private message xiaobian.
Import gl def fun(): print gl._a print gl._b fun()Copy the code
“Constant”
Python does not provide reserved words for defining constants. You can define a constant class to achieve constant function.
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() raise self.consterror, "Can't rebind const(%s)" %name self.__dict__[name]=value import sys sys.Copy the code
[Data type]
1 The number types in Python are integer, long, floating point, Boolean, and complex.
2 Python has no character types
Python has no ordinary types inside it. Any type is an object.
4 If you want 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 three types of string types: single, double, and triple quotation marks. Single and double quotes have the same effect. Python programmers prefer single quotes, while C/Java programmers tend to use double quotes for strings. You can enter single quotation marks, double quotation marks, or newline characters in three quotation marks.
[Operators and Expressions]
1 Python does not support the increment and decrement operators. For example, I ++/ I – is wrong, but I +=1 is ok.
2 1/2 will be equal to 0.5 before python2.5, and 0 after python2.5.
3 is not equal to PI! =, < >
4 is equal to theta equals theta
5 in the logical expression, “and” means logical and, “OR” means logical or, and “not” means logical not
【 Control Statements 】
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 Nesting of conditions: if (expression 1) : if (expression 2) : statement 1 ELif (expression 3) : statement 2... Else: Statement 3 elif (expression N) :... The else:... 4 Python does not have a switch statement. 5 loop statement: while(expression) :... The else:... 6 loop statement: for variable in set:... The else:... 7 Python does not support the c-like for(I =0; i<5; For x in range(0,5,2): print xCopy the code
[Array related]
Tuple: A data structure built into 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. That is, tuples cannot be modified after they are created. Tuples tend to represent a row of data, and the elements in a tuple represent different data items. You can think of tuples as unmodifiable arrays. The following is an example of creating a tuple:
Tuple_name =(” apple “, “banana”, “grape”, “orange”) 2 List: Like tuples, lists are also composed of a set of elements. Lists can be added, removed, and found, and the values of elements can be changed. Lists are arrays in the traditional sense. The following is an example of creating a list:
List =[” apple “, “banana”, “grage”, “orange”] appends an element to the end using the append method and removes an element using the remove method.
Dictionary: a collection of key-value pairs. Values in the dictionary are referenced by keys. Keys and values are separated by colons, key-value pairs are separated by commas, and are contained in a pair of curly braces. The following is an example:
Dict = {” a “:” apple “, “b”, “banana”, “g” : “grage”, “o”, “orange”} 4 sequence: the sequence is a set of index and the ability to slice. Tuples, lists, and strings belong to sequences.
【 Function correlation 】
1 A Python program consists of packages, modules, and functions. A package is a collection of modules. A module is a collection of functions and classes that deal with a class of problems.
A 2 pack is a toolkit that does a specific task.
3 packages must contain an __init__.py file that identifies the current folder as a package.
Python programs are made up of modules. A module is a group of related functions or code organized into a file. A file is a module. A module consists of code, functions, and classes. Import modules use import statements.
The purpose of the package 5 is to achieve program reuse.
6 A function is a piece of code that can be called several times. The following is an example of a function definition:
Def arithmetic (x, y, operator) : the result = {" + ": x + y," - ": x, y," * ": x * y,"/" : the x/y}Copy the code
The return value of a function can be controlled by return.
[String related]
1 Format output:
Format = "%s%d" % (str1,num) print formatCopy the code
2 string merge with + :
Str1 = "hello" str2 = "world" result = str1 + str2Copy the code
String interception can be done by indexing/slicing or by using the split function.
4. Slice the string:
The word = "world" print word [3-0]Copy the code
5 Python uses == and! = to perform string comparisons. If you compare two variables of different types, the results must be different.
[Document handling]
1. Simple file processing:
The context = "hello, world" f = file (" hello. TXT ", 'w') f.w rite (context); f.close()Copy the code
2 Files can be read using the readline(), readlines() and read functions.
3 Write files using the write() and writelines() functions
【 Objects and Classes 】
Python uses the class reserved word to define a class. Capitalize the first character of the class name. When a programmer needs to create a type that cannot be represented by a simple type, he defines a class and then creates an object using the defined class. Class Fruit: def grow(self): print “Fruit grow”
When an object is created, it contains three properties: handles, properties, and methods. How to create an object:
Fruit = fruit () fruit.grow() 3 Python does not protect type modifiers
The four classes of methods are also divided into public and private methods. Private functions cannot be called by functions outside the class, and private methods cannot be called by external classes or functions.
Python uses the “staticMethod ()” or “@staticMethod” instruction to convert normal functions to static methods. Static methods are equivalent to global functions.
6 Python’s constructor is called __init__ and its destructor is called __del__
7 How to use inheritance:
The class Apple (Fruit) : def...Copy the code
Mysql > Connect to mysql
Use MySQLdb module to operate MySQL database. The example 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()Copy the code
Hope the article content can bring you help
From basic Python scripting to Web development, crawlers, data analysis, data visualization, machine learning, and more. Those who want these materials can pay attention to xiaobian, and make small letters in the background