Python Knowledge Summary

Source: Internet
Author: User
Tags print print python script
Python Knowledge Summary

I. Introduction of Python

1. Introduction to Python

Python is an interpretive, interactive, object-oriented, beginner language.

2. Python Features

① Easy to learn

② Easy to read

③ Easy to maintain

④ a wide range of standard libraries

⑤ Interactive mode

⑥ Portable

⑦ Extensible

⑧ Database

⑨gui programming

⑩ Scalability

3, Python support tab completion function:

>>> Import Readline,rlcompleter

>>> readline.parse_and_bind (' Tab:complete ')

The above two sentences can be written to a py file, directly import can

Ipython to save the command history, you must install Sqlite-devel

4. Python Installation

#tar-JXVF python-3.4.3.tar.bz2

#cd Python3.4.3

#./configure [--prefix=/usr/local/python3]

#make && make Install

Note: ①python is a system-dependent package, can only be updated, cannot be deleted, and Yum version must be compatible with Python, after the upgrade of Python, yum must be specified to use the lower version. The following actions are appropriate:

#mv/usr/bin/python/usr/bin/python-2.6.bak Backup

#ln-S/usr/local/bin/python3.4/usr/bin/python creating a soft connection

#python –V Perform a version scan

② Modifying the Yum configuration file to make it work correctly

#vim/usr/bin/yum

Modify one of the/usr/bin/python to/usr/bin/python2.6

③ If the above settings are complete and error, remember to modify the environment variables

#vim/etc/profile

5. Python Run script

5.1, the way of implementation

#python

5.2. Precautions:

① in version python3.0 and above, print becomes a function. So you must use the print () format, and the previous version does not have parentheses

>>> print (' Hello Man ')

② when using Python in interactive mode, note that only Python commands can be entered, that it is necessary to print statements in scripts, and that expression effects can be printed automatically in an interactive script without the need to enter completed print statements

>>> Print (2**10)

③ in interactive mode, it is necessary to execute the conforming statement and add ":" to represent that the statement has not been executed. And you must use a blank line to represent the end-of-line statement

>>> for I in range (4):

... print (i)

...

0

1

2

3

4

④ to ensure indentation unification, otherwise error

5.3. Python script run

①bash Bang Introduction

#!/usr/bin/python

#!/usr/bin/env Python (this is the recommended format, and it's not easy to have a Python-school-based problem)

Second, Python programming

1, the definition of variables

1.1. Naming rules for variables

① variable names can only start with letters and underscores (_)

② variable names can be made up of letters, numbers, and underscores

③ variable name is case sensitive, the lamp and lamp are not the same variable name

1.2. Assigning values to variables

① Assignment operation

Variable name = variable Value

② Assigning a string to a variable, you need to enclose the string in quotation marks, otherwise the error

>>> name = Wdd

Traceback (most recent):

File "<stdin>", line 1, in <module>

Nameerror:name ' WDD ' is not defined

③ Increment Assignment

>>> x = 1

>>> x = x+1

>>> x

2

④ Multiple Assignments

>>> x=y=z=2

>>> x

2

>>> y

2

>>> Z

2

>>>

⑤ "Multivariate Assignment"

>>> x,y,z=1,2,3

>>> x

1

>>> y

2

>>> Z

3

2. Data type

2.1. Numerical type

① Plastic Surgery

>>> 123+321

44

② floating Point type

>>> 3.14*3

9.42

2.2. String type

① string Definitions

>>> name = ' Wdd '

>>> Name

' Wdd '

>>> Print (name)

Wdd

>>> dir (name) #查看字符串支持的方法帮助

[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ' ', ' __getitem__ ', ' __getnewargs__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ Mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' _formatter_field_name_split ', ' _formatter_parser ', ' capitalize ', ' Center ', ' count ', ' decode ', ' encode ', ' endswith ', ' expandtabs ', ' find ', ' format ', ' Index ', ' isalnum ', ' isalpha ', ' isdigit ' ', ' islower ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' lstrip ', ' partition ', ' replace ', ' rfind ', ' Rinde X ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' splitlines ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' transl ' Ate ', ' upper ', ' Zfill ']

>>> name.replace (' Wdd ', ' Shuaige ') #把wdd替换为shuaige

' Shuaige '

>>> name.replace (' W ', ' Cool ') Replace W with cool

' Cooldd '

>>> Help (Name.replace) #查看具体的方法帮助

② single double quotation mark in string

Single and double quotation marks in a string, used to contain strings

>>> persion = ' name ', ' height '

>>> persion

(' name ', ' height ')

>>> info= "I ' m a good man" #在双引号中嵌套单引号 without escape character

>>> Info

"I ' m a Good man"

>>> Print (info)

I ' m a good man

③ calling special characters in a string

If you use the escape character \ to cause special characters to lose meaning, the special escape characters in the system are as follows:


Escape character Action

\ \ reserved backslash

\, keep single quotation marks

\b Backspace

\ nthe line break

\ t Horizontal tab

\v Vertical Tab


>>> name = ' My\tname\tis\tjack '

>>> name #直接输出变量name, escape character is not recognized

' My\tname\tis\tjack '

>>> print (name) #调用print函数, can be used normally

My name is Jack

④raw Escape Character Suppression

You may not need to use escape characters in certain situations, such as using System files in Windows

>>> path = ' C:\new\text.txt '

>>> Print (PATH)

C:

EW Ext.txt # System will recognize \ n and \ t as escape characters, causing the command to fail

>>> Path = R ' C:\new\text.txt '

>>> print (path) #使用raw字符串关闭转义机制

C:\new\text.txt

⑥ multi-line string in triple quotation marks

>>> info = "" "My Name is

... jack, I ' m a honest

... man "" "

>>> Info #直接调用变量不能正确显示

"My name Is\njack, I ' m a Honest\nman"

>>> Print (info) #需要使用print函数显示

My name is

Jack, I ' m a honest

Mans

Note: Do not confuse comments, comments are not assigned

Sequence manipulation of ⑦, strings

The value in the variable holds the first value in index 0, and 1 holds the second value

>>> name = ' Jack '

>>> Len (name)

4

>>> Name[0]

' J '

>>> Name[1]

A

>>> Name[2]

C

>>> Name[3]

K

The index can also be reversed, that is, 1 represents the last value, and 2 represents the second-lowest value

>>> Name[-1]

K

>>> Name[-2]

C

The string also supports the Shard operation, which is to take out part of the variable

>>> Name[1:3]

' AC ' #取出变量中第一位到第三位结束 (not including fourth bit) content

>>> Name[2:4]

' CK '

>>> name[1:] #取出变量从第一位到变量结束

' Ack '

>>> Name[:2] #取出变量从开头 • End of first bit (not including second digit)

' Ja '

3. List

A list is also a sequence that supports all operations on a sequence. The list is somewhat similar to an array, but much more powerful than an array. The list does not have a data type limit, and you can define different types of objects in a list. Additionally, the list does not have a fixed size, and you can increase and decrease the size of the list as needed. And the values in the list can be changed.

1. List operation

Definition of a table

>>> info = [' Jack ', ' a ', ' M ']

>>> Info

[' Jack ', ' a ', ' M '] #此列表中的值既有字符串也有整型

>>> Len (info) #查看列表长度

Sequence actions for a list

>>> Info[0] #取出列表值第一位

' Jack '

>>> Info[:-1] #从列表开头取值到倒数第二位 (does not include the countdown first)

[' Jack ', ' 22 ']

>>> info[0:] #从列表开头取到最后一位

[' Jack ', ' a ', ' M ']

Special methods for tables

The values in the list can be changed, and the size of the list can be changed.

>>> info = [' Jack ', ' a ', ' M ']

>>> info[0]= ' Mark ' #改变列表中0的值

>>> Info

[' Mark ', ' a ', ' M ']

>>> Help (Info) #查看列表可以使用的方法

>>> info.append (' American ') #追加

>>> Info

[' Mark ', ' a ', ' M ', ' American ']

>>> Info.pop (1) #删除第一位的值

' 22 '

>>> Info

[' Mark ', ' M ', ' American ']

>>> Info.insert (1,22) #在第一位插入新值22

>>> Info

[' Mark ', ' M ', ' American ']

>>> digit=[1,3,2,5,4]

>>> Digit

[1, 3, 2, 5, 4]

>>> Digit.sort () #排序

>>> Digit

[1, 2, 3, 4, 5]

>>> Digit.reverse () #进行序列翻转

>>> Digit

[5, 4, 3, 2, 1]

2. Nested list

The list has an attribute that supports arbitrary nesting, can be nested in any combination, and can be nested at multiple levels. This feature can implement a data matrix, or a multidimensional array

>>> m=[[1,2,3],[4,5,6],[7,8,9]]

>>> m

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> M[1][2]

6

>>> m[1][2]=10 #查看第二个子列表中的第三个值

>>> M[1][2] #改变第二个子列表中的第三个值

10

4, tuple (tuple)

Tuples can be viewed as an immutable list, and tuples can also support sequence operations. Easy to store and extract a set of values

>>> information= (' Lusi ', ' F ')

>>> Information

(' Lusi ', ' F ')

>>> Information[0] #提取第一个值

' Lusi '

>>> Information[1] #提取第二个值

18

Note: The values in the tuple cannot be changed, only the entire tuple can be re-assigned (the string cannot change the value, it can only be redefined)

>>> ID (information)

3073641204L #元组中的内存ID号

>>> information= ("SDF", "Ahlk", 67)

>>> info= (three-way) #给元组重新赋值之后, the ID number will change, representing a new tuple appears

>>> ID (info)

3074861852L

>>> a= (1,) #定义只有一个元素的元组时, need to add commas, otherwise it will be recognized as shaping

>>> type (a)

<type ' tuple ' >

>>> b= (1)

>>> Print

Print print (

>>> print (type (b))

<type ' int ' >

>>> t= (All-in-a-kind) #可以把元组中的值赋予多个变量 (multivariate assignment of a variable)

>>> T

(1, 2, 3)

>>> a,b,c=t

>>> A

1

>>> b

2

>>> C

3

5. Dictionaries

The dictionary is written in {}, and is assigned using the key: Value method. The data in the dictionary is saved in pairs, and the value of the dictionary can be changed by saving the two-dimensional data. But the order of the dictionaries is unreliable, that is, the order in which we set up the dictionary does not necessarily coincide with the order in which we output the dictionary.

Definition of ① Dictionary

>>> info={"name": "Jack", "Age": $, "Sex": "M"} #定义字典

>>> Info #查看字典

{' Age ': ' Name ': ' Jack ', ' sex ': ' M '}

>>> info[' name '] #查看字典某一个键的值

' Jack '

>>> info[' country ']= ' American ' #在字典中添加新的 "key: Value"

>>> Info

{' Country ': ' American ', ' age ': ' Name ': ' Jack ', ' sex ': ' M '}

Sort the keys in the ② dictionary

The order of the dictionaries is unreliable, that is, the order in which we build our dictionaries is not necessarily the same as our output dictionaries.

>>> info={"name": "Jack", "age": +, "sex": "M"}

>>> Info #字典输出的顺序并不一定

{' Age ': ' Name ': ' Jack ', ' sex ': ' M '}

>>> for key in sorted (info): #for循环, there are several values in info, looping several times

... print (key, ' is ', Info[key]) #sorted函数把info变成列表, sort with sort, then output with for loop, note indent

...

(' Age ', ' is ', 20)

(' name ', ' is ', ' Jack ')

(' Sex ', ' is ', ' M ')

6. File type

The file type is the primary interface for Python's external files on the computer. If you are creating a file object, you need to call the built-in open function, pass it as a string to it, an external file name, and a string that handles the pattern.

>>> f = open (' Test ', ' W ')

#使用open函数, define the file name and processing mode, which will be established in the Linux current directory

Supported modes:

' R ' is opened by default in read form

' W ' first clears the file at open for writing

' x ' creates a new file and opens it for writing

' A ' open write, append to the end of an existing file

>>> dir (f) #查看该对象支持的方法

[' __class__ ', ' __delattr__ ', ' __doc__ ', ' __enter__ ', ' __exit__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init ' __ ', ' __iter__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __ Subclasshook__ ', ' close ', ' Closed ', ' encoding ', ' errors ', ' Fileno ', ' flush ', ' isatty ', ' mode ', ' name ', ' newlines ', ' Next ' , ' read ', ' Readinto ', ' readline ', ' readlines ', ' seek ', ' softspace ', ' Tell ', ' truncate ', ' write ', ' writelines ', ' xreadline S ']

>>> f.write (' My name is jack\n ') #通过write方法向文件中写入数据

>>> F.write (' My Age is 22\n ')

>>> f.close () #关闭对文件的写操作

>>> F.close ()

>>> t = open (' Test.txt ', ' R ') #使用r处理模式, opening file

>>> test = T.read () #赋予变量

>>> Test #直接调用变量不能正确查看内容

' My name is jack\nmy-22\n '

>>> print (test) #使用print函数显示内容

My name is Jack

My age is 22

7. Boolean value

is to determine whether an expression is true

>>> 1 = = 2

False

>>> 1 < 2

True

>>> 1 > 2

False

>>> 1 <= 2

True

8. View variable types

>>> name = ' Jack '

>>> age = 20

>>> type (name)

<type ' str ' >

>>> type (age)

<type ' int ' >

>>> age = ' #加入引号 ', into a string

>>> type (age)

<type ' str ' >

9. Python annotations

①# Comment a Word

② ""

Content #注释一段内容

'''

10. Module

Every Python source file with the end of the extension py is a module, and other scripts can import the module and use all the contents of the entire module. Module China can contain functions and other script content.

The search path for the module

Module search, search local location, and then follow the SYS.PATH environment variable to search

You do not need to write the suffix name when importing the module

>>> Import Myhello

You need to add the path of your saved script to the path of Python, otherwise it will not be imported correctly

# cd/usr/local/python27/lib/python2.7/site-packages/

# Vim My.pth

/root #把自己的python脚本目录放入此目录中以. PTH End

Take Help

>>> Help (' modules ')

#查询系统支持的所有模块, including system built-in modules and user-import modules

>>> help (' sys ') #查看模块具体帮助

>>> Import Math #引入数学计算模块

>>> dir (math) #查看此模块支持的函数

>>> Help (Math) #查看此模块具体的注释

>>> Help (Math.sin) #查看此模块中函数的注释

>>> Math.PI #调用模块中一个函数

3.141592653589793

How to import ③python modules

Import Module

Import module name as new name #给模块起一个别名

From module name import variable name

Reload Module

The imported module runs directly in Python, but imports are resource-intensive and can only be executed once (unless you exit to re-enter the session)

If you want to import the module repeatedly and execute it, you need to use reload

>>> Import Imp #在python中, reload is no longer a built-in function, so you must import

>>> imp.reload (Myhello) #在模块中, call reload function

Or

>>> from imp import reload #从模块中导入reload函数

>>> Reload (Myhello)

Hello

<module ' Myhello ' from ' Myhello.pyc ' >

Python Knowledge Summary

  • 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: info-contact@alibabacloud.com 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.