Python knowledge summary

黄舟
Release: 2016-12-15 15:17:01
Original
2012 people have browsed it

Python knowledge summary

1. Introduction to python

1. Introduction to Python

Python is an interpreted, interactive, object-oriented language for beginners.

2. python features

①Easy to learn

②Easy to read

③Easy to maintain

④An extensive standard library

⑤Interactive mode

⑥Portable

⑦Expandable

⑧Database

⑨GUI Programming

⑩Scalability

3. python supports tab completion function:

>>> import readline,rlcompleter

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

You can write the above two sentences into a py file and import it directly

ipython If you want 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 dependency package and can only be updated, not deleted, and The version of yum must match python. After upgrading python, you must specify the lower version of yum. The corresponding operations are as follows:

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

#ln -s /usr/local/bin/python3.4 /usr/bin/python Create a soft connection

#python -V Perform version scan

②Modify the yum configuration file to make it work properly

#vim /usr/bin/yum

Modify /usr/bin/python to /usr/bin/python2 .6

③ If you still get an error after completing the above settings, remember to modify the environment variables

#vim /etc/profile

5. python running script

5.1. Execution method

#python

5.2. Notes:

①In python3.0 and above, print becomes a function. Therefore, the print() format must be used for execution, and the previous version did not use brackets

>>> print('hello man')

② When using python in interactive mode, please note: you can only enter python commands; in the script The print statement is necessary, and the expression effect can be automatically printed in the interactive script. There is no need to enter the completed print statement

>>> print (2**10)

③In interactive mode, it needs to be executed To match the statement, ":" needs to be added, which means that the statement has not been executed. And a blank line must be used to represent the end of the matching statement

>>> for i in range(4):

... print(i)

...

0

1

2

3

4

④ Make sure the indentation is uniform, otherwise an error will occur

5.3, python script running

①Introduction to bash bang

#!/usr/bin/python

#!/usr/bin/env python (It is recommended to use this format, it is not easy to have the problem that the python version cannot be executed)

2. python programming

1. Definition of variables

1.1. Naming rules of variables

① Variable names can only use letters and Variable names starting with an underscore (_)

②Variable names can be composed of letters, numbers and underscores

③Variable names are case-sensitive, lamp and LAMP are not the same variable name

1.2. Assignment of variables

①Assignment operation

Variable name = variable value

②Assign a string to the variable. You need to enclose the string in quotes, otherwise an error will be reported

>>> name = wdd

Traceback (most recent call last):

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

NameError: name 'wdd' is not defined

③Incremental assignment

>>> x = 1

>>> x = x+1

>>> >>> y

2

>>> =1,2,3

>>> 2.1. Numeric type

①Integer

>>> 123+321

44

②Floating point type

>>> 3.14*3

9.42

2.2. Type

①String definition

>>> name = 'wdd'

>>> name

'wdd'

>>> print(name)

wdd

> ;>> dir(name) #View the method help supported by string

['__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', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

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

'shuaige'

>>> name.replace('w','cool') 把w替换为cool

'cooldd'

>>> help(name.replace) #查看具体的方法帮助

②字符串中单双引号

在字符串中单双引号一致,用于包含字符串

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

>>> persion

('name', 'height')

>>> info="I'm a good man" #在双引号中嵌套单引号,不用转义符

>>> info

"I'm a good man"

>>> print(info)

I'm a good man

③在字符串中调用特殊字符

如果使用转义符,将使特殊字符失去含义,系统中特殊的转义字符如下:


转义符                                     作用

   \                                     保留反斜杠

    ,                                    保留单引号

   b                                       退格

   n                                       换行

   t                                   水平制表符

   v                                  垂直制表符

   


>>> name = 'mytnametistjack'

>>> name #直接输出变量name,转义符无法识别

'mytnametistjack'

>>> print(name) #调用print函数,可以正常使用

my    name    is    jack

④raw转义符抑制

在某些特定情况下可能不需要使用转义符,如在windows中使用系统文件

>>> path = 'c:newtext.txt'

>>> print(path)

c:

ew    ext.txt # 系统会把n和t识别为转义符,导致命令失败

>>> path = r'c:newtext.txt'

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

c:newtext.txt

⑥三重引号编写多行字符串

>>> info = """my name is

... jack, I'm a honest

... man"""

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

"my name isnjack, I'm a honestnman"

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

my name is

jack, I'm a honest

man

注意:不要和注释搞混,注释没有赋值

⑦, Sequence operation of strings

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

>>> name = 'jack'

>>> ; len(name)

4

>>> name[0]

'j'

>>> name[1]

'a'

>>> name[2]

'c'

>>> name[3]

'k'

index can also be reversed, that is, -1 represents the last value, -2 represents the second to last value Value

>>> name[-1]

'k'

>>> name[-2]

'c'

Strings also support sharding operations, that is, taking out variables Part of the content in

>>> name[1:3]

'ac' #Get the content from the first to the third digit (excluding the fourth digit) in the variable

>> > name[2:4]

'ck'

>>> name[1:] #Take out the variable from the first position to the end of the variable

'ack'

>>> name [:2] #Extract the variable from the beginning to the first position (excluding the second position)

'ja'

3. List

The list is also a type of sequence and supports all operations on the sequence. Lists are similar to arrays, but much more powerful. Lists have no data type restrictions, and objects of different types can be defined in a list. In addition, the list does not have a fixed size, and the size of the list can be increased and decreased as needed. And the values ​​in the list can be changed.

1. List operation

Definition of table

>>> info = ['jack','22','M']

>>> info

['jack', '22', 'M'] #The values ​​in this list are both strings and integers

>>> len(info) #View the length of the list

Sequence operations on the list

>>> ; info[0] #Get the first value of the list

'jack'

>>> info[:-1] #Get the value from the beginning of the list to the second to last value (excluding the first to last)

['jack', '22']

>>> info[0:] #Get the last digit from the beginning of the list

['jack', '22', 'M']

Special methods of tables

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

>>> info = ['jack','22','M']

> >> info[0]='mark' #Change the value of 0 in the list

>>> info

['mark', '22', 'M']

>>> ; help(info) #Methods that can be used to view the list

>>> info.append('American') #Append

>>> info

['mark', '22', 'M', 'American']

>>> info.pop(1) #Delete the first value

'22'

>>> info

['mark', 'M', 'American']

>>> info.insert(1,22) #Insert a new value 22 in the first position

>>> info

['mark', 22 , 'M', 'American']

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

>>> digit

[1, 3, 2, 5, 4]

>>> digit.sort() #Sort

>>> digit

[1, 2, 3, 4, 5]

>>> digit.reverse () #Perform sequence flip

>>> digit

[5, 4, 3, 2, 1]

2. List nesting

The list has a feature that supports arbitrary nesting and can be They can be nested in any combination and can be nested at multiple levels. This feature can implement data matrices or multi-dimensional arrays

>>> 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 #View the third value in the second sublist

>>> m[1][2] #Change the second sublist The third value of

10

4. Tuple (tuple)

A tuple can be regarded as an immutable list, and a tuple can also support sequence operations. You can easily store and retrieve a set of values

>>> information=('lusi',18,'F')

>>> information

('lusi', 18, 'F' ')

>>> information[0] #Extract the first value

'lusi'

>>> information[1] #Extract the second value

18

Note: The value in the tuple cannot be changed, the entire tuple can only be reassigned (the value of the string cannot be changed, it can only be redefined)

>>> id(information)

3073641204L #Memory in the tuple ID number

>>> information=("sdf","ahlk",67)

>>> info=(1,2,3) #After reassigning the tuple, the ID number will change, which means a new tuple appears

>>> id(info)

3074861852L

>>> a=(1,) #When defining a tuple with only one element, you need to add a comma, otherwise it will be recognized as an integer

>>> type(a)

< ;type 'tuple'>

>>> b=(1)

>>> print

print print(

>>> print(type(b))

>>> t=(1,2,3) #You can assign the values ​​​​in the tuple to multiple variables (like multivariate assignment of variables)

>> ;> t

(1, 2, 3)

>>> a,b,c=t

>>> a

1

>>> b

2

> Data and dictionary values ​​can also be changed. However, the order of the dictionary is not reliable, that is, the order when we create the dictionary is not necessarily the same as the order when we output the dictionary.

①The definition of dictionary

>>> info={"name":"jack","age":20,"sex":"M"} #Definition dictionary

>>> info #View dictionary

{'age': 20, ' name': 'jack', 'sex': 'M'}

>>> info['name'] #View the value of a key in the dictionary

'jack'

>>> info['country']='American' #Add new "key: value" in the dictionary

>>> info

{'country': 'American', 'age': 20, 'name ': 'jack', 'sex': 'M'}

②The ordering of keys in the dictionary

The order of the dictionary is not reliable, that is, the order when we create the dictionary is not necessarily the same as the order when we output the dictionary

>>> info={"name":"jack","age":20,"sex":"M"}

>>> info #The order of dictionary output is not necessarily

{'age': 20, 'name': 'jack', 'sex': 'M'}

>>> for key in sorted(info): #for loop, there are several values ​​​​in info , loop several times

... print(key, 'is', info[key]) #sorted function turns info into a list, sorts it with sort, and then uses a for loop to output, pay attention to the indentation

...

('age', 'is', 20)

('name', 'is', 'jack')

('sex', 'is', 'M')

6. File type

File types are Python's main interface to external files on your computer. If you want to create a file object, you need to call the built-in open function, passing it an external file name and a processing mode string in the form of a string.

>>> f = open('test','w')

#Use the open function to define the file name and processing mode, and the file will be created in the current directory of Linux

Supported modes:

'r' opens for reading by default

'w' first clears the file before opening it for writing

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

'a' opens it for writing, appending to an existing End of file

>>> dir(f) #View the methods supported by this object

['__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', 'xreadlines']

>>> f.write('my name is jackn') #Write data to the file through the write method

>>> f.write('my age is 22n')

>>> f.close() #Close the file Write operation

>>> f.close()

>>> t = open('test.txt', 'r') #Use r processing mode to open the file

>> ;> test = t.read() #Assign the variable

>>> test #Directly calling the variable cannot correctly view the content

'my name is jacknmy age is 22n'

>>> print(test) #Use the print function to display the content

my name is jack

my age is 22

7. The Boolean value

is to determine whether the expression is true

>> 1 < = 2

True

8. View variable type

>>> name = 'jack'

>>> age = 20

>>> type(name)

>>> type(age)

>>> age = '18' #Add quotation marks to turn into characters String

>>> type(age)

9. Python comments

①# Comment a sentence

②'''

Content #Comment a piece of content

'''

10. Module

Every python source code file ending in py is a module. Other scripts can import this module and use all the content in the entire module. Modules can contain functions and other script content.

Module search path

Module search, first search the local location, and then search according to the sys.path environment variable

When importing the module, you do not need to write the suffix name

>>> import myhello

You need to add the path where you save the script to the python path, otherwise it cannot be imported correctly

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

# vim my.pth

/root # Put your own python script directory into this directory and end with .Pth

Get help

>>> help('modules')

#Query all modules supported by the system, including system built-in modules and user imports Module

>>> help('sys') #View module specific help

>>> import math #Introduce mathematical calculation module

>>> dir(math) #View this Functions supported by the module

>>> help(math) #View the specific comments of this module

>>> help(math.sin) #View the comments of the functions in this module

>> ;> math.pi #Call a function in the module

3.141592653589793

③The import method of python module

import module

import module name as new name #Give the module an alias

from module name import variable name

Reload module

The imported module is run directly in python, but importing consumes resources, so it can only be executed once (unless you exit and re-enter the session)

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

> ;>> import imp #In python, reload is no longer a built-in function, so it must be imported

>>> imp.reload(myhello) #In the module, call the reload function

or

> ;>> from imp import reload #Import the reload function from the module

>>> reload(myhello)

hello

Python Knowledge summary

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template