程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python basics] a summary of basic Python grammar knowledge, personal collation to ~ ~ ~ (a self-made Python mind map is attached at the end of the text)

編輯:Python

Python Basic grammar summary

  • One 、Python brief introduction
    • 1. Classification of programming languages :
      • (1) Classification method 1 :
      • (2) Classification 2 :
    • 2.Python The principle of program execution :
  • Two 、Python Basic grammar
    • 1. Basic grammar
      • (1) notes
      • (2) Code indentation
      • (3) Statement wrap
    • 2. Variables and naming
      • (1) Variable
      • (2) name
    • 3. Identifiers and keywords
      • (1) identifier
      • (2) keyword
    • 4. Simple numeric type
      • (1) integer
      • (2) floating-point
      • (3) The plural
      • (4) Boolean type
      • (5) Numeric type conversion
    • 5. Operator
    • 6. Numerical operation function
    • 7. Basic input and output
  • 3、 ... and 、Python character string
    • 1. The introduction of string
    • 2. Index of a string
    • 3. Slice of string
    • 4. String operation
      • (1) Basic operators
      • (2) Processing function
      • (3) processing method
    • 5. String output
      • (1)format Method
      • (2)f-string Method
  • Four 、Python Structural control
    • 1. Judgment statement
    • 2. Loop statement
      • (1)for loop : Traversal cycle
      • (2)while loop : condition loop
    • (3) Nesting of loops
    • 3.Python Other statements
      • (1)break sentence : End the cycle ( Open circuit )
      • (2)continue sentence : End this cycle ( A short circuit )
      • (3)pass sentence : Empty statement ( placeholder )
      • (4)else sentence : The extended mode of the loop ——else Reward mechanism
    • 4. exception handling
      • (1) Exception types
      • (2)try-except sentence
  • 5、 ... and 、Python Combined data types
    • 1. List the type
      • (1) List Overview
      • (2) Definition list
      • (3) Loop through the list
      • (5) List operation
        • increase :
        • Delete :
        • Change :
        • check :
      • (6) Common operators in the list 、 function
      • (7) List derivation
    • 2. A tuple type
      • (1) Definition of tuple
      • (2) Tuple operation
      • (3) Commonly used operators in tuples 、 function
      • (4) Be careful :
    • 3. Dictionary type
      • (1) Dictionary definition
      • (2) Common operation of dictionaries
      • (3) Built in functions and methods commonly used in dictionaries
        • Built in functions :
        • Common methods :
    • 4. Collection types
      • (1) Definition of set
      • (2) Operations on collections
        • increase :
        • Delete :
        • Change :
        • check :
      • (3) The operation of sets
  • 6、 ... and 、Python function
    • 1. Function definition and call
    • 2. The parameters of the function
    • 3. The return value of the function
    • 4. Four types of functions
    • 5. Nested calls to functions
    • 6. Scope of variable
    • 7. Anonymous function and recursive function
      • (1) Anonymous functions
      • (2)map function
      • (3)filter function
      • (4) Recursive function
    • 8. Date time function
    • 9. Random number function
    • 10. Closure
  • 7、 ... and 、Python File operations
    • 1. Type of file
    • 2. Opening and closing of files
    • 3. Read the contents of the file
    • 4. Write data file
  • 8、 ... and 、Python Module operation
    • 1. Basic use of modules
    • 2. Module making
    • 3.Python In the package
    • 4. Module release
    • 5. Module installation
  • Self made mind map :

One 、Python brief introduction

1. Classification of programming languages :

(1) Classification method 1 :

① A compiled :
A whole is first compiled into a semi-finished file , High repeatability
example :C/C++
② interpreted :
Compile the code line by line
example :Python
(Python It is partial to explanation , But in fact, it is semi interpreted and semi compiled )

(2) Classification 2 :

① Static language
It needs to be defined before use
example :C/C++
② Dynamic language ( Also called scripting language )
There is no need to define the data type of variables during programming
example :Python

2.Python The principle of program execution :

Source code m.py —(Python Interpreter )> Bytecode m.pyc —( Runtime PVM)> result
① First pass the source code through Python The interpreter compiles into bytecode
② Forward the compiled bytecode to Python virtual machine (PVM) In the implementation of

Two 、Python Basic grammar

1. Basic grammar

(1) notes

① Single-line comments
python Single line comments in the are marked with # start
② Multiline comment
Multiline comments start and end with three quotation marks

(2) Code indentation

① Indentation refers to the blank area before the beginning of each line of code , Used to represent the inclusion and hierarchical relationship between codes
②Python Strict indentation is used to indicate the format framework of the program .
③ Code indentation needs attention : Be strict and clear 、 Affiliation 、 Consistent length

(3) Statement wrap

python It's usually a sentence written one line at a time , But if the statement is very long and needs to wrap , have access to \ To achieve
Attention should be paid to :
stay []、{}、() The statement in , There is no need to wrap lines with backslashes

2. Variables and naming

(1) Variable

Python It's dynamic language , Variables do not need to be defined first , Whatever you want , Similar to a label
① Variables are placeholders used to hold and represent data
②python Variables in are used to store data , Variable uses identifier ( name ) To express ,
The process of associating identifiers is called naming
③ The definition of variables must follow the naming rules
④ Assignment symbols can be used = Assign values to variables , Change the value of the variable

(2) name

① Naming is the process of associating a variable or other program element with a name or identifier
② Naming rules :
Case letters 、 Numbers 、 Underline and Chinese characters and their combinations
③ Be careful :
Case sensitive
The first character cannot be a number
Cannot be the same as reserved words
No spaces in between
There is no limit to length

3. Identifiers and keywords

(1) identifier

Named , The naming rules are the same as those for variables

(2) keyword

It's also called reserved word , It refers to the identifier defined and reserved by the programming language

4. Simple numeric type

(1) integer

① Consistent with the concept of integer in Mathematics , There is no limit on the value range
② By default, the result of operation between hexadecimals is displayed in decimal system

(2) floating-point

① Floating point type is consistent with the concept of real number in mathematics , Represents a numeric value with a decimal , Must have a decimal part , The decimal part can be 0
②E or e Indicates that the base is 10, The following integer represents the exponent , The positive and negative use of the index ± Express
③ The operation precision of integer is higher than that of floating-point number
( because python The values in are all converted to binary and calculated directly , If it is a floating-point number, binary operation , The results may be approximate )

(3) The plural

①Python The middle complex number can be regarded as a binary ordered real number pair (a,b), Express a+bj
among a It's the real part ,b It's the imaginary part
② Both real and imaginary parts are floating point

(4) Boolean type

① Boolean data has only two values :True and False
②bool No operation
③ All the emptiness is False, All non emptiness is True
The following Boolean values are False:
None、False、0、0.0、0.0+0.0j、 An empty string 、 An empty list 、 An empty tuple 、 An empty dictionary

(5) Numeric type conversion

①type(x)
The variable x Make type judgment , For any data type
②int(x)
take x Convert to an integer
Be careful : When converting a floating-point type to an integer type , The decimal part will be discarded directly ( Do not use rounding )
③float(x)
take x Convert to a floating point number , The default is six decimal places
④complex(a,b)
Create a complex number

5. Operator

(1) Arithmetic operator
x//y: Divide and conquer , Returns the integer part of the quotient
x**y: power , return x Of y The next power
(2) Assignment operator
Synchronous assignment statement :
x,y=y,x
(3) Compound assignment operator
(4) Compare assignment operators
(5) Logical operators
and、 or、 not
(6) member operator
in 、 not in 
Operator priority

6. Numerical operation function

(Python in 6 Built in functions related to numerical operations )
(1)abs(x): The absolute value
seek x The absolute value of
x It can also be in the plural , But since both the real part and the imaginary part are floating point numbers , So the absolute value of a complex number is also a floating point number
abs(-3+4j) #5.0

(2)divmod(x,y): Excepting
(x//y,x%y), The output is in binary form ( Also called tuple type )
Calculation x and y The result of the division of , Returns two values , Namely x and y Multiplication and division quotient of x//y, as well as x And y The remainder of x%y
(3)pow(x,y) or pow(x,y,z): Power operation
x** y or x ** y%z , Power operation
(4)round(x) or round(x,d): rounding
Yes x rounding , Retain d Decimal place , No parameter d Returns the rounded integer value

Be careful :
Not all .5 Will carry , Will all x.5 There are two types of situations :
use “ Odd in, even out ” The way of operation , When x For even when ,x.5 Not carry ; When x In an odd number of ,x.5 carry

(5)max(x1,x2…xn): Maximum
Return the maximum value inside ,n There is no limit
(6)min(x1,x2…xn): minimum value
Return the minimum value inside ,n There is no limit

7. Basic input and output

(1)input() Input function
① Format :
A. Variable =input()
B. Variable =input(“ Suggestive text ”)

② Return results :
String type

③ Be careful :
input() The data result is read through line feed , Therefore, you cannot input multiple lines at the same time
To enter multiple newline values at the same time , Through the loop +input Statements in conjunction with

④ format conversion :
s=int(input())# Cast
s=eval(input())

(2)eval() Evaluation function
① effect :
Remove the quotation marks from the string , Evaluate automatic string recognition as a type
eval(‘hello’) # error
eval(‘“hello”’) # Output hello

② Be careful :
eval() The result of processing the string contents can be saved in variables
hello=5
eval(‘hello’)

③ If the user wants to enter a number and calculate , The following combinations can be used to implement
Variable =eval(input(“ Suggestive text ”))

That is, when you need to cast a string , Generally, cast is not used directly , It's about using eval() Evaluation function

(3)print() Output function
① effect :
Output the result of the operation
There are two output formats : Default output format and specific format output

② Default format output :
A. Only for outputting strings
print(“ The Chinese Dream , My dream ”) # The Chinese Dream , My dream
print() # Output blank lines

B. Used only to output one or more variables
value=123.456
print(value,value)

C. By default :
print(,sep="',end=“_”)
sep: Specify in the same print() In the sentence , The separator between variables , If it is not written, it defaults to blank
end: Specify multiple print() Separator between statements , If it is not written, it defaults to line feed

③ Specific format output :
print(‘ A word description %_’ %( Variable ,…))

3、 ... and 、Python character string

1. The introduction of string

(1) Definition of string :
A string is a data type that represents text , According to the content of the string , It is divided into :
① Single line string : Enclosed by a pair of single or double quotation marks is a single line string , The two functions are the same
② Multiline string : Surrounded by a pair of three single quotation marks or three double quotation marks is a multiline string , The two functions are the same

Be careful : Why? Python There will be single quotation marks and double quotation marks in the ?

print(‘ Today is really ’ happy ’ A day of ’)# error , Will regard beauty as a variable
print(‘ Today is really " happy " A day of ’)# correct , Today is really " happy " A day of

(2) Escape character
Escape character by backslash \ guide , The characters next to them form a new meaning

2. Index of a string

(1) meaning :
The retrieval of a character in a string becomes an index
(2) form :
< character string >[ Serial number ]
(3) classification :
Each character in the string has a corresponding subscript , There are two subscript numbering methods : Positive increase and negative decrease
If the length of the string is L:
Positive increase :0~L-1 Increase to the right
Reverse decrement :-1~-L Decrease to the left

3. Slice of string

(1) meaning :
The retrieval of a substring or interval in a string is called slicing
(2) form :
s[start : end : step]
The default is to switch back from , Positive increase
step: Positive and negative represent the direction , Size represents step size
(3) Be careful :
① The slice interval is left closed and right open , That is, the string obtained from start To end Substring of , Index not included end
② The index sequence number of slices can be mixed with positive increasing sequence number and negative response sequence number

4. String operation

(1) Basic operators

①x+y: Connect two strings x And y
②xn or nx : Copy n Substring x
③x in s : If x yes s String , return True, Otherwise return to False

(2) Processing function

①len(x): Return string x The length of
②str(x): Returns any type x The corresponding string form
③chr(x): return unicode code x The corresponding string
④ord(x): Returns a single character representation of unicode code
⑤oct(x): Return integer x The lowercase string of the corresponding octal encoded number
⑥hex(x): Return integer x The lowercase string of the corresponding hexadecimal encoded number

(3) processing method

①find Method
effect : Check whether the string contains substrings
form :str.find(sring,beg=0,end=len(ser))
str Specifies the string to retrieve
beg Start index , The default is 0
end End index , The default is the length of the string
If you find , Returns the index , If you can't find it , The result is -1

②index Method
effect : Check if there is a substring in the string
form :str.index(sring,beg=0,end=len(ser))
str Specifies the string to retrieve
beg Start index , The default is 0
end End index , The default is the length of the string
Returns the index , If you can't find it , Report errors

③replace Method
effect : Replace the old string with the new string
form :str.replace(old,new[max])
old The string to be replaced
new New string , Used for replacement old character string
max Optional string , Replace no more than max Time

④split Method
effect : Slice a string by specifying a separator
form :str.split(string=“”,num=str.count(string))
string With string Slice for separator str
num Number of divisions , Optional parameters , If num There is a specified value , Then just divide num+1 A string
Result generation list ( Can achieve string to list )
Be careful :
If string Not in str in , Will not slice , Or the original string

⑤join Method
effect : Merge all the elements in parentheses into a new string
form :str.join(seq)
seq The sequence of elements to connect
str Connector
Returns a new string generated by connecting elements in a sequence through a specified character
Be careful :
When seq When of string type , Will be separated by each character
When seq When it is a list type , Will be separated by each comma in the list , Because the list is separated by commas

⑥count Method
effect : Count the number of characters in a string
form :
str.count(sub,start=0,end=len(str))
sub Search string
start Where the string starts searching
end Where to end the search in the string

⑦upper Method
effect : Convert lowercase letters to uppercase letters
form :str.upper()

⑧lower Method
effect : Convert capital letters to lowercase letters
form :str.lower()

5. String output

(1)format Method

format Method : Formatted string
form :
< Template string >.format(< Comma separated parameters >)
Template string : A string consisting of a string and a slot , Used to control the display effect of strings and variables
Slot : Use braces {} Express , Equivalent to placeholder , Corresponding format() Comma separated parameters in method

(2)f-string Method

explain :
①f-string Method : Format string constant
②f-string It is not a string constant in nature , It's an expression that evaluates at run time
③ about Python3.6 And later versions , Recommended f-string Formatting strings
form :
f-string In form f or F Modifier LED string (f’xxx’ or  F’xxx’), In curly braces {} Indicate the field to be replaced
f"{content:format}"
content: Replace and fill in the contents of the string , It could be a variable 、 Expression or function, etc
{:format}: And format The method is similar to
Be careful :
① quotes :
f-string Quotation marks used inside braces cannot conflict with quotation mark delimiters outside braces , It can be switched flexibly according to the situation
② The backslash :
Quotation marks outside curly brackets can also be used \ escape , But you can't use... In braces \ escape
③ Curly braces :
f-string Outside the braces if you need to show braces , Two consecutive braces should be entered { { and }}

Four 、Python Structural control

1. Judgment statement

(1) Simple branching structure :if sentence

(2) Choose a branching structure :if…else sentence
Be careful :
There is also a more concise expression in two branches :
< expression 1>if< Conditions >else< expression 2>
It is suitable for the case that all statement blocks contain only simple expressions .

(3) Multi branch structure :if…elif…else

(4) Nesting of branches
Nesting of branches means that there are branches in the branch , namely if The statement also contains if sentence

2. Loop statement

(1)for loop : Traversal cycle

① form :
for < Loop variable > in < Traversal structure >:
                    < Sentence block >

② The traversal structure can be a string 、 file 、range() function 、 Combined data types

③range() Three uses of functions :
Generate a sequence of numbers
A.range(N): 0~N-1
B.range(start,end): start~end-1
C.range(start,end,step): start~end-1, But there are steps : Partition step Take one of them

④for The logical structure of a statement :
Each item in the traversal structure is assigned to the loop variable , Each loop variable executes the statement block , The loop ends when the traversal of the traversal structure is completed

(2)while loop : condition loop

① form :
while < Conditions >:
          < Sentence block >

② When conditions are not met , The loop ends ;
When the conditional expression is always true when , Wireless loop

③while Loops can be used to implement multiple lines of input

(3) Nesting of loops

Whether it's while Cycle or for loop , Each of them can contain another cycle , Thus, the nesting of loops is formed

3.Python Other statements

(1)break sentence : End the cycle ( Open circuit )

(2)continue sentence : End this cycle ( A short circuit )

Then execute the next cycle

(3)pass sentence : Empty statement ( placeholder )

It doesn't work , As a placeholder , Maintain the integrity of the program structure

(4)else sentence : The extended mode of the loop ——else Reward mechanism

① When for loop 、while After the loop runs normally , The program will continue else What's in the sentence .
else Statement is executed and ended only after the loop is executed normally
②else Statements are often used to judge the execution of a loop
③else Reward : You can put in the loop else Think of it as a reward , Only the program completely executes the loop , To perform else What's in the statement
Used in the loop break perhaps return It will not be executed later else,continue Yes else Statement has no effect

4. exception handling

(1) Exception types

When Python There will be abnormal information when an error is reported in the program , The most important exception information is the exception type .
It shows the cause of the exception , It is also the basis for the program to handle exceptions

(2)try-except sentence

① form :
try:
    Program statements to run
except+ Exception types :
    The statement that the exception wants to output
except:
      Other abnormal error statements you want to output

② and if-else The difference between sentences :
else The statement cannot be followed directly by the content , and except Then you can follow the content , But the content must be an exception type name

③ Be careful :
If you don't add try-except sentence , If there is any abnormality , The editor will automatically help us identify , Return exception , It can also be modified manually

5、 ... and 、Python Combined data types

1. List the type

(1) List Overview

① The list is Python A data structure in , Can be used to store different types of data
② The list index is from 0 At the beginning , You can access the values of the elements in the list by subscript index
③ The types of elements in the list can be different , Lists can contain lists , The list has no length limit
A. Store certain data in a certain form ( There is an order of precedence between the elements in the list )
B. Store a group with a length of L The data of ( The length is 0—L, Variable length )
④ Be careful :
Variable data type :
As the program changes, the elements defined by the data type itself can be modified The data type of is variable
otherwise , Is an immutable data type
character string 、 Tuples are immutable data types
list 、 Dictionaries 、 The collection is of variable data type

(2) Definition list

①[]
s=[]# Create an empty list
s=[1,2,3,4,5]

②list()
s=list()# Create an empty list
s=list(“12345”)
s=list(12345)# error ,list() Sequence type or range()

(3) Loop through the list

① Use for Loop through the list
A. Value traversal
for i in s:
    print(i)
B. Subscript traversal
for i in range(len(s)):
    print(s[i])
② Use while Loop through the list  

(4) A list is a sequence type , So we have a common way to use sequences
There are only three sequence types : character string 、 list 、 Tuples
The same thing :
① section
② Indexes
③+( Splicing )、*( repeat )
④in、not in  Existence does not exist
⑤len() Find sequence length

(5) List operation

increase :

①append()
append( Single element x): Add the last element to the list x
②insert()
insert( To be inserted into i The subscript position of , Single element x): To the... Of the list i Bit add element x
③extend()
extend( Sequence ): Add a sequence to the end of the list ( Not just lists ) The elements in

Delete :

①del
Use reserved words , Combined with slice delete
②s.pop(i)
i Is the subscript of the deleted element , Delete the last digit without default
③s.remove(x)
x You want to delete the value of the element , If it is repeated, only the first one will be deleted
④s.clear()
No need to add parameters , Clear the entire list , Empty list , But the list still exists

Change :

① Modify by index slice assignment
s=[0,1,2,3,4,5]
s=s[0:3]
print(s)  #[0, 1, 2]
Be careful :
If there are more elements after the position of the slice , Will increase more and supplement less
If there are fewer elements after the position of the slice , Can cut normally , Then add these elements ( First cut off the left element , Fill in the elements on the right )

②copy()
Make a copy of the list
Be careful : Why not use it directly = Well ?
Because in python Variable names in can be regarded as labels , Take it and use it
b=a: Assignment is equivalent to variable name assignment , The actual space has not changed
b=a[:] or b=a.copy() : Will open up a separate space

check :

①in、not in 
in( There is ): If it exists, the result is True, Otherwise False
not in( non-existent ): If it does not exist, the result is True, Otherwise False
②index(x)
Find elements in list x For the first time, the subscript value appears
( If it doesn't exist , Will report a mistake , Exception handling is available )
③count(x)
Find elements in list x Number of occurrences
Sort :
①reverse()
Reverse list
②sort()
Default ascending sort
s.sort(reverse=True) null
s.sort(key=)key This is followed by a function , Must be a sort rule , Sort in a specific order

(6) Common operators in the list 、 function

① Common operators : List connector +、 List replicator *
② Common functions :
min()
max()
sum()
When using, the elements in the list must be of the same data type

(7) List derivation

Similar to the double branch selection structure , Use other lists to create a new list

① Common writing :
s=[x2 for x in range(1,11)]
Equivalent to :
s=[]
for x in range(1,11):
    s.append(x
2)

② Open writing :
s=[x2 for x in range(1,11) if x%20]
Equivalent to :
s=[]
for x in range(1,11):
    if x%2
0:
        s.append(x
2)

2. A tuple type

(1) Definition of tuple

① meaning :
Tuples are immutable , Equivalent to an immutable list
② establish :
Use () Parentheses or tuple() function

(2) Tuple operation

① Because the element value in the element cannot be modified , So tuples themselves cannot be incremented 、 Delete 、 Change the operation
Can only be indexed 、 section 、 And find the length and other sequence operations

② If you want to change the value in the tuple , You can convert tuples to lists , After modification , Convert to tuple

③del keyword . An element value cannot be deleted from a tuple , But you can delete an entire tuple
a=(1,2,3,4,5)
del a
# This tuple a It is deleted , Not in memory

(3) Commonly used operators in tuples 、 function

① Common operators : Tuple connector +、 Tuple replicator *
② Common functions :
min(tuple)
max(tuple)
sum(tuple)
When used, the elements in tuples must be of the same data type
len(tuple): Calculate the number of elements in the tuple
tuple(seq): Convert the list to tuples

(4) Be careful :

When a tuple contains only one element , You need to add a comma after the element , Otherwise, parentheses will be used as operators
tup1=(12)
tup2=(12,)
print(tup1,tup2)

3. Dictionary type

(1) Dictionary definition

① meaning :
Dictionary is another variable container model , And can store any type of object .

② form :
Each key value of the dictionary  key:value  Yes, with a colon  :  Division , Comma between each key value pair  ,  Division , The whole dictionary is enclosed in curly brackets  {}  in  , The format is as follows :
d = {key1 : value1, key2 : value2 }

③ Be careful :
A.dict  As  Python  Keywords and built-in functions , Variable names are not recommended to be named  dict.
B. key key The only thing is that , If you repeat the last key value pair, the previous one will be replaced , value value It doesn't need to be the only one .
C. value value You can take any data type , But the key key Must be of immutable type , Such as a string , A number or tuple .
D. The difference between lists and dictionaries :
list : Subscript —— value , The subscript index has a size range , So it's an ordered sequential structure
Dictionaries : key —— value   , Keys are unordered and cannot be repeated , So the elements in the dictionary are out of order , Cannot find by subscript , Or slice it
E.
a=[] # Definition list  
a=() # Define tuples
a={} # Definition dictionary

(2) Common operation of dictionaries

① Create a dictionary
A.{}
B.dict() function
② Retrieve dictionary elements
A. Use in Operator to retrieve key in dicts
B. Use keywords to retrieve dict[“key”]
③ Add and modify dictionary elements
Using key indexes + assignment :dicts[key]=value
④ Delete dictionary elements
A.del
Can be used to delete the entire dictionary , You can also delete one of these elements
B.clear() Method
Only the data in the dictionary will be cleared , But dictionaries still exist , Empty dictionary

(3) Built in functions and methods commonly used in dictionaries

Built in functions :

①cmp(dict1, dict2)
Compare two dictionary elements .
②len(dict)
Count the number of dictionary elements , That's the total number of bonds .
③str(dict)
The printable string representation of the output Dictionary .
④type(variable)
Returns the type of variable entered , If the variable is a dictionary, return the dictionary type .
⑤sorted(dict)
With key Value to sort the dictionary , The default is unicode Code size

Common methods :

①dict.clear()
Delete all elements in the dictionary
②dict.copy()
Returns a shallow copy of a dictionary
③dict.fromkeys(seq[, val])
Create a new dictionary , In sequence  seq  The middle element is the key of the dictionary ,val  Is the initial value of all keys in the dictionary
④dict.get(key, default=None)
Returns the value of the specified key , If the value is not returned in the dictionary default value
⑤dict.has_key(key)
If the key is in the dictionary dict Back in true, Otherwise return to false
⑥dict.items()
Return traversable as a list ( key ,  value )  Tuple array
⑦dict.keys()
Return all keys of a dictionary as a list
⑧dict.setdefault(key, default=None)
and get() similar ,  But if the key does not exist in the dictionary , The key will be added and the value will be set to default
⑨dict.update(dict2)
Put the dictionary dict2 Key / Value pair update to dict in
⑩dict.values()
Returns all values in the dictionary as a list
①①pop(key[,default])
Delete dictionary given key  key  The corresponding value , The return value is the deleted value .key Value must be given .  otherwise , return default value .
①②popitem()
Returns and deletes the last pair of keys and values in the dictionary .

4. Collection types

(1) Definition of set

① meaning :
Python The set in set Is included 0 An unordered combination of one or more non repeating data items
② Use scenarios :
Because the elements in the collection are not repeatable , It can be used when it is necessary to de duplicate one-dimensional data or repeat data processing
③ establish :
have access to { } perhaps set() Function to create a collection
Note that to create an empty collection, you must use set() instead of {}, because {} Is used to create an empty dictionary

(2) Operations on collections

increase :

①s.add(x)
Put the element x Add to collection s in , If it already exists , No action will be taken
②s.update(x)
Update collection , Put the element x Add to collection s in ,x Can be a list , Tuples , Dictionaries

Delete :

①s.pop()
From the collection s Randomly delete an element from the , An exception is returned when the collection is empty
②s.remove(x)
From the collection s Delete element x, If x Not in the assembly , Return exception
③s.discard(x)
From the collection s Delete element x, If x Not in the assembly , No exception will be returned

Change :

s.copy()
Copy Collection , Returns a copy of the collection

check :

①s.isdisjoint(t)
Judgment set s And collection t Whether the same element exists in , If you don't have the same element , return True
②len(s)
len Function returns a collection s The number of elements in

(3) The operation of sets

(Python The concept of set in is consistent with that in mathematics , The method can be used and checked )
hand over &
Bad -
and |
repair ^

6、 ... and 、Python function

1. Function definition and call

(1) What is a function ?
Functions are organized , Reusable code snippets

(2) Definition of function
Python Define function use def keyword , Format :

def Function name ( parameter list ):
        The body of the function
       return Return value list
(3) Function call
After defining the function , If you want to use a function , You need to call the function , Format :

Function name (< Argument list >)

Be careful : Functions must be defined before they are used

2. The parameters of the function

(1) Positional arguments
When a function is called , By default , Arguments will be passed to formal parameters in positional order
(2) Assign parameters
How to enter arguments according to the name of the formal parameter
(3) Default parameters ( Also called optional parameter )
When defining a function , You can set default values for formal parameters of functions , This parameter is called the default parameter
Be careful :
① If no value is passed in for the default parameter , The default value is used directly ; If the default parameter passes in a value , The new value passed in is used instead of
② Parameters with default values must be at the end of the parameter list , Otherwise, an exception will be reported when the program runs
(4) Variable parameters ( Also called indefinite length parameter )
You can accept any parameter when defining a function , It can be 0 individual ,1 One or more
form :
The parameter name is preceded by an asterisk *, Or add two asterisks **
Be careful :
① Add an asterisk to the variable : Will store all unnamed variable parameters , For tuples
② A variable with two asterisks : Will store named parameters , For the dictionary

3. The return value of the function

(1) The return value of the function is to use return Statement to complete
(2)return Statements can return 0 individual 、1 The result of one or more function operations
Be careful : Save as tuple when multiple values are returned , Without parameter value return Statement returns None

4. Four types of functions

(1) No parameter , Functions with no return value
(2) No parameter , Function with return value
(3) With parameters , Functions with no return value
(4) With parameters , Function with return value

5. Nested calls to functions

Functions and functions can be nested

6. Scope of variable

(1) Namespace
① Purpose :
To avoid conflicting names of variables ,Python Introduced the concept of namespaces
② meaning :
A namespace is a name to object mapping , It's like a dictionary : The key name is the name of the variable , The value is the value of the variable .
(2) Scope
Namespaces exist independently of each other , Combining these hierarchies of namespaces is scope
(3) local variable
① meaning :
A variable defined inside a function
② Scope :
The scope of a local variable is within a function .
It is only valid within the definition of the function , Once the function ends, it disappears
(4) Global variables
① meaning :
Define a global scope outside the function
② Scope :
Global variables can be accessed throughout the program
③ Be careful :
If the global variable and the local variable have the same name , Then what is accessed in the function is the local variable
④ Grammatical form :
globa < Global variables >

7. Anonymous function and recursive function

(1) Anonymous functions

① meaning :
Formally, an anonymous function is a function without a name .
But anonymous functions are not really nameless , Instead, the function name is returned as the result of the function

② form :
< Function name >=lambda [ Parameter list ]: Function return value expression

③ example : The following two are equivalent
def s(a,b):
    return a+b
print(s(2,3))

s=lambda a,b:a+b
print(s(2,3))

④ When to use lambda function ?
A. The definition is simple , A function that can be represented on a line , Returns a function type
B. It can be done with map、sorted、filter Use a combination of

⑤ Be careful :
A.lambda Expressions cannot contain branch or loop statements
B.lambda Function can only return the value of one expression , Anonymous functions cannot call directly print
C. Can be lambda Expression as an element of the list , So as to realize the function of jump table , That is, the list of functions

(2)map function

① effect :
Map the specified sequence .
That is, each element in the parameter sequence calls function function , Save the result returned after each call as an object
② Definition :
map( Function name , iterator )
③ example :
func=lambda x:x+2
result=map(func,[1,2,3,4,5])
print(list(result))

(3)filter function

① effect :
Filter the specified sequence
② Definition :
filter( Function name , Sequence or iterator )
③ example :
func=lambda x:x%2
result=filter(func,[1,2,3,4,5])
print(list(result))

(4) Recursive function

① meaning :
The program calls itself
② form :
Call yourself directly or indirectly when defining a function
③ The idea of solving problems :

if The question is simple enough :
    Solve the problem directly
    Return solution
else:
    The problem is decomposed into one or more smaller problems isomorphic with the original problem
    Solve these smaller problems one by one
    Combine the results into , Get the final solution
    Return solution

8. Date time function

( Use now and check now )

① Time stamp
Generally speaking , The time stamp indicates that the 1970 year 1 month 1 Japan 00:00:00 Start offset in seconds
② Formatted time string
③ time tuples
(1) Time function
( Use time library )
(2) Date function
( Use calendar library )

9. Random number function

random The functions in the library are mainly used to generate pseudo-random number sequences of various distributions
Random numbers are determined by random seeds , The probability is certain 、 Visible , It is called a pseudo-random number
(1)random.random()
Randomly generate one [0,1.0] The floating point number between , Closed interval
(2)random.seed( Random seeds )
Initialize the pseudo-random number generator , If no seeds are provided or random seeds =None, By default, the current system timestamp is used as the random seed
The random seed must be an integer
(3)random.uniform(a,b)
Random return [a,b] or [b,a] The floating point number between
(4)random.randint(a,b)
Random return [a,b] A random integer between , It must be guaranteed here b>a
(5)random.randrang([start],stop,[step])
Random return [start,stop) An integer between , Parameters step Step length
(6)random.choice(seq)
From non empty sequence seq Randomly select an element in the
(7)random.shuffle(x,[random])
Random disorder of variable sequences x Sort order of inner elements , Be commonly called " Shuffle "
(8)random.sample(seq,k)
From the specified sequence seq Random access to k Elements are returned as fragments

10. Closure

(1) Internal and external functions
Python It supports nesting , If you define another function inside a function ,
External functions are called external functions , Internal functions are called internal functions
Be careful :
① The essence of an internal function is a local variable ( A function is a variable )
② Internal functions cannot be called directly outside the function , Internal function call
(2) Closure
Definition :
If an internal function references a variable in the scope of an external function , Then this inner function is called closure
( Put the local variable ( Internal function ) Introduced into the global environment for use , This is the closure operation )

Be careful :
① A closure is a function that can be dynamically generated by another function , And you can create and change the value of variables created outside the function
② Function closures remember the scope of the outer function

Conditions of use :
① Closures must have nested functions
② Nested functions need to reference variables in external functions ( Include arguments to external functions )
③ The external function needs to return the nested function name as the return value

example :
def outer(a,b):
    def inner(c,d):
        return c+d+a+b
    return inner
print(outer(1,2)(2,4))

7、 ... and 、Python File operations

1. Type of file

Depending on the file storage format , Can be divided into text files and binary files

2. Opening and closing of files

(1) File processing steps : open -> operation -> close
(2) Opening of files :
< Variable name >=open(< file name >,< Turn on mode >)
file name : Can write absolute path , Write relative paths under the same source file
Turn on mode : text file or Binary read or Write
(3) Closing of files :
< file name >.close()
Use memory buffers to cache file data

3. Read the contents of the file

(1) read :
①read(): Read all file contents
②readline(): Read a line of file content
③readlines(): Read all lines of the file
(2) Write :
①write(str): The string str write file
②writelines(seq_of_str): Write multiple lines to a file , Parameters seq_of_str Objects that can be iterated
(3)seek() Method :
Pointer to file — That's the cursor
call seek() Method can manually move the position of the pointer

4. Write data file

CSV Files are mainly used for data organization and processing , Divide the data into three types :
① One-dimensional data : linear ( list 、 aggregate 、 Tuples )
② Two dimensional data : Also known as relationship , Row and column matrix ( form )
③ Multidimensional data : Expansion of two-dimensional data ( Commonly used dictionary key value pairs represent )

8、 ... and 、Python Module operation

1. Basic use of modules

The concept of modules :
The program you write is called a module
The import module
①import  sentence
②from…import  sentence
③from…import*  sentence
_name_ attribute :
Commonly used in custom module testing
if name==‘main’

2. Module making

3.Python In the package

Each level of directory usually contains one int.py file

4. Module release

5. Module installation

Self made mind map :


( Copyright ownership , It's not easy to create )


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved