Python is an interpreted, interactive, object-oriented language for beginners. 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
④ A broad standard library
⑤ Interaction mode
⑥ Portable
7. scalability
Slave Database
⑨ GUI Programming
Scalable ingress
3. python supports the tab complementing function:
>>> Import readline, rlcompleter
>>> Readline. parse_and_bind ('Tab: complete ')
You can write the preceding two sentences into a py file and directly import them.
To save command history, ipython 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. it can only be updated and cannot be deleted. The yum version must be compatible with python. After python is upgraded, you must specify a lower version for yum. Follow these steps:
# Mv/usr/bin/python/usr/bin/python-2.6.bak backup
# Ln-s/usr/local/bin/python3.4/usr/bin/python to create a soft connection
# Python-V version scanning
② Modify the yum configuration file to make it work normally
# Vim/usr/bin/yum
Change/usr/bin/python to/usr/bin/python2.6.
③ If an error is reported after the preceding settings are completed, modify the environment variable.
# Vim/etc/profile
5. run the script in python
5.1. execution method
# Python
5.2. notes:
① In python3.0 or later versions, print becomes a function. Therefore, the print () format must be used for execution, and the previous version does not use parentheses.
>>> Print ('Hello man ')
② When using python in interactive mode, Note: Only the python command can be entered. printing statements in the script is required, and the expression effect can be automatically printed in the interactive script, no print statement required
>>> Print (2 ** 10)
③ In interactive mode, the statement must be executed and ":" must be added, indicating that the statement has not been completed. In addition, an empty line must be used to indicate the end of the statement.
>>> For I in range (4 ):
... Print (I)
...
0
1
2
3
4
④ Ensure uniform indentation; otherwise, an error occurs.
5.3 run python scripts
① Bash bang introduction
#! /Usr/bin/python
#! /Usr/bin/env python (this format is recommended, so it is not easy to run a school-based python program)
II. python programming
1. variable definition
1.1 variable naming rules
① The variable name can only start with a letter or underscore (_)
② The variable name may consist of letters, numbers, and underscores
③ Variable names are case sensitive. the input lamp and LAMP are not the same variable names.
1.2 assign values to variables
① Assignment operation
Variable name = variable value
② Assign a value to the variable. enclose the string in quotation marks. Otherwise, an error is returned.
>>> Name = wdd
Traceback (most recent call last ):
File" ", Line 1, in
NameError: name 'wdd' is not defined
③ Incremental 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. numeric type
① Integer
>>> 123 + 321
44
② Floating point type
>>> 3.14*3
9.42
2.2. string type
① String definition
>>> Name = 'wdd'
>>> Name
'Wdd'
>>> Print (name)
Wdd
>>> Dir (name) # view the method help supported by the string
['_ Add _', '_ class _', '_ ins _', '_ delattr __', '_ doc _', '_ eq _', '_ format _', '_ ge _', '_ getattribute __', '_ getitem _', '_ getnewargs _', '_ getslice _', '_ gt _', '_ hash __', '_ init _', '_ le _', '_ len _', '_ lt _', '_ mod __', '_ mul _', '_ ne _', '_ new _', '_ reduce _', '_ performance_ex __', '_ repr _', '_ rmod _', '_ rmul _', '_ setattr _', '_ sizeof __', '_ str _', '_ subclasshook _', '_ formatter_field_name_split', '_ formatter_parser', 'capitalize', 'center', 'count ', 'Decode', 'enabled', 'enabledwith', 'pandtabs ', 'Find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit ', 'islower ', 'isspace', 'istitle', 'isupper', 'join', 'ljust ', 'lower', 'lstrip', 'Partition', 'replace ', 'fappin', 'rindex', 'Partition UST ', 'rpartition', 'rsplits', 'rdstrip', 'splits ', 'splitlines', 'startswith', 'strip ', 'swapcase', 'title', 'translate', 'uppper ', 'zfill']
>>> Name. replace ('wdd', 'shuaige ') # replace wdd with shuaige.
'Shuague'
>>> Name. replace ('W', 'cool ') replaces w with cool
'Cooldd'
>>> Help (name. replace) # View The help method
② Double quotation marks in a string
The double quotation marks are consistent in the string. they are used to contain strings.
>>> Persion = 'name', 'height'
>>> Persion
('Name', 'height ')
>>> Info = "I'm a good man" # enclose single quotes in double quotes without escape characters
>>> Info
"I'm a good man"
>>> Print (info)
I'm a good man
③ Call special characters in strings
If the escape character \ is used, the meaning of the special characters will be lost. the special escape characters in the system are as follows:
Escape character
\ Retain backslash
\, Keep single quotes
\ B return
\ N line feed
\ T horizontal tab
\ V vertical tab
>>> Name = 'My \ tname \ tis \ tjack'
>>> Name # directly output the variable name, which cannot be identified by escape characters
'My \ tname \ tis \ tjack'
>>> Print (name) # Call the print function, which can be used normally.
My name is jack
④ Raw escape character suppression
In some specific circumstances, escape characters may not be required, such as using system files in windows.
>>> Path = 'C: \ new \ text.txt'
>>> Print (path)
C:
Ew ext.txt # The system recognizes \ n and \ t as escape characters, leading to command failure
>>> Path = r'c: \ new \ text.txt'
>>> Print (path) # use raw strings to disable the escape mechanism
C: \ new \ text.txt
6. write multi-line strings in triple quotes
>>> Info = "" my name is
... Jack, I'm a honest
... Man """
>>> Info # The variables directly called cannot be correctly displayed.
"My name is \ njack, I'm a honest \ nman"
>>> Print (info) # use the print function to display
My name is
Jack, I'm a honest
Man
Note: Do not mix with comments. comments are not assigned a value.
7. sequential operations on strings
The value in the variable is 0 in the index, the first value is saved, and 1 the second value is saved.
>>> Name = 'Jack'
>>> Len (name)
4
>>> Name [0]
'J'
>>> Name [1]
'A'
>>> Name [2]
'C'
>>> Name [3]
'K'
The index can also be reverse indexed, that is,-1 represents the last value, and-2 represents the second to last value.
>>> Name [-1]
'K'
>>> Name [-2]
'C'
The string also supports sharding, that is, extracting part of the variable content.
>>> Name [1: 3]
'AC' # retrieve the content from the first to the third (excluding the fourth) of the variable.
>>> Name [2: 4]
'Ck'
>>> Name [1:] # retrieve the variable from the first to the end of the variable
'Ack'
>>> Name [: 2] # retrieve the variable from the beginning to the end of the first digit (excluding the second digit)
'Ja'
3. list
A list is also a sequence that supports all operations on the sequence. Lists are similar to arrays, but they are much more powerful than arrays. The list has no restrictions on data types. you can define different types of objects in a list. In addition, the list does not have a fixed size. you can increase or decrease the size of the list as needed. The values in the list can be changed.
1. list operations
Table definition
>>> Info = ['Jack', '22', 'M']
>>> Info
['Jack', '22', 'M'] # The values in this list include both strings and integers.
>>> Len (info) # view the list length
List sequence operations
>>> Info [0] # retrieve the first value of the list
'Jack'
>>> Info [:-1] # From the beginning of the list to the second to last (excluding the first to last)
['Jack', '22']
>>> Info [0:] # obtain the last digit from the beginning of the list
['Jack', '22', 'M']
Special table methods
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 available 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 () # insert a new value 22 in the first place
>>> 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 () # reverse the sequence
>>> Digit
[5, 4, 3, 2, 1]
2. list nesting
The list has a feature that supports any nesting, can be nested in any combination, and can be nested in multiple layers. This feature can implement data matrices or multi-dimensional arrays.
>>> M = [[, 3], [, 6], [, 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 third value in the Second sublist
10
4. tuple)
Tuples can be seen as an unchangeable list, and tuples can also support sequential operations. Allows you to conveniently store and extract 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 values in the tuples cannot be changed. you can only assign a value to the entire tuples (the values of strings cannot be changed, but can only be redefined)
>>> Id (information)
3073641204L # memory ID in the tuples
>>> Information = ("sdf", "ahlk", 67)
>>> Info = (, 3) # After you assign a value to the tuples, the ID number changes, indicating that a new tuple appears.
>>> Id (info)
3074861852L
>>> A = (1,) # When defining a tuple with only one element, you must add a comma. Otherwise, it will be recognized as an integer.
>>> Type ()
>>> B = (1)
>>> Print
Print (
>>> Print (type (B ))
>>> T = (, 3) # you can assign values in the tuples to multiple variables (such as the multivariate value assignment of variables)
>>> T
(1, 2, 3)
>>> A, B, c = t
>>>
1
>>> B
2
>>> C
3
5. dictionary
The dictionary is written in {} and assigned a value using the "key: value" method. The data in the dictionary is saved in pairs. it is suitable for storing two-dimensional data and the value of the dictionary 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 consistent with the order when we output the dictionary.
① Definition of dictionary
>>> Info = {"name": "jack", "age": 20, "sex": "M"} # define a dictionary
>>> Info # View dictionaries
{'Age': 20, 'name': 'Jack', 'Sex': 'M '}
>>> Info ['name'] # view the value of a dictionary key
'Jack'
>>> Info ['country'] = 'American '# Add a new "key: value" to the dictionary"
>>> Info
{'Country': 'American ', 'age': 20, 'name': 'Jack', 'Sex': 'M '}
② Sorting of dictionary types
The order of the dictionary is not reliable, that is, the order when we create the dictionary is not necessarily consistent with the order when we output the dictionary.
>>> Info = {"name": "jack", "age": 20, "sex": "M "}
>>> Info # the output sequence of the dictionary is not necessarily
{'Age': 20, 'name': 'Jack', 'Sex': 'M '}
>>> For key in sorted (info): # for loop. There are several values in info and the number of cycles
... Print (key, 'is, info [key]) # The sorted function converts info into a list, sorts it with sort, and uses for loop output. Note the indentation.
...
('Age', 'is, 20)
('Name', 'is ', 'Jack ')
('Sex', 'is', 'M ')
6. file type
The file type is the main interface of python for external files on the computer. If you want to create a file object, you need to call the built-in open function to pass 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. the file will be created in the current linux directory.
Supported modes:
'R' is opened as read by default.
'W' first clears the file and writes it when it is opened.
'X' creates a new file and opens it for writing.
'A' open the write and append it to the end of an existing file.
>>> Dir (f) # view the methods supported by this object
['_ Class _', '_ delattr _', '_ doc _', '_ enter __', '_ exit _', '_ format _', '_ getattribute _', '_ hash _', '_ init __', '_ iter _', '_ new _', '_ reduce _', '_ performance_ex _', '_ repr __', '_ setattr _', '_ sizeof _', '_ str _', '_ subclasshook _', 'close', 'closed ', 'encoding', 'errors', 'fileno', 'flush', 'isatty ', 'mode', 'name', 'newlines', 'next', 'read ', 'readin', 'readline', 'readlines', 'seek ', 'softspace', 'Tell', 'truncate', 'write', 'writelines ', 'xreadlines']
>>> F. write ('My name is jack \ n') # write data to the file through the write method
>>> F. write ('My age is 22 \ n ')
>>> F. close () # close the write operation on the file
>>> F. close ()
>>> T = open('test.txt ', 'r') # use the r processing mode to open the file
>>> Test = t. read () # assign a variable
>>> Test # directly calling the variable cannot view the content correctly.
'My name is jack \ nmy age is 22 \ n'
>>> Print (test) # use the print function to display content
My name is jack
My age is 22
7. Boolean value
Is to determine whether the 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 (age)
>>> Age = '18' # enclose the string with quotation marks.
>>> Type (age)
9. python annotations
① # Comment a sentence
② '''
Content # comment a piece of content
'''
10. module
The python source code file ending with the py extension is a module. other scripts can import this module and use all the content in the entire module. The module China can contain functions and other script content.
Module search path
Module search: first searches for the local location, and then searches according to the environment variable of sys. path.
When importing a module, you do not need to write a suffix
>>> Import myhello
Add the path for saving the script to the path of python. Otherwise, the script cannot be imported correctly.
# Cd/usr/local/python27/lib/python2.7/site-packages/
# Vim my. pth
/Root # Put your python script directory into this directory and end with. Pth
Get help
>>> Help ('modules ')
# All modules supported by the query system, including the built-in system modules and user import modules
>>> Help ('sys ') # view the module's help details
>>> Import math # introduce the mathematical computing module
>>> Dir (math) # View functions supported by this module
>>> Help (math) # view the comments of this module
>>> Help (math. sin) # view the function comments in this module
>>> Math. pi # call a function in the module.
3.141592653589793
③ Import method of the python module
Import Module
Import module name as new name # alias for the module
From module name import variable name
Reload module
The imported module runs directly in python, but the import is resource-consuming, so it can only be executed once (unless you exit and re-enter the session)
If you want to re-import the module and execute it, you need to use reload
>>> Import imp # In python, reload is no longer a built-in function, so you must import
>>> 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