1,Python Two kinds of programming methods of computer : interactive ( Run as you go ) And file format ( Main methods ; Batch run results )
2, Everything is the object , Each object is identified by the (id()), type (type()) Sum value (print()) identification .
3,Python Using value based memory management , Different variables are assigned to the same value ,ID equally , But it only applies to -5 to 256 Integer and short string of .
4, Built in functions (BIF),68 individual , View by :dir(builtins)
classification :
Numerical data type :int,float,complex,bool,decimal,fractions
Sequence data type : character string (string), list (list), Yuanzu (tuple),bytes,bytearray
Collection data type :set,frozenset
Dictionary data type :dict
Immutable data type : numerical value Number, character string String, Yuanzu Tuple
Variable data types : list List, Dictionaries Dict, aggregate Set
5,
Binary :0b/0B start
octal number system :0o/0O start
hexadecimal ;0x/0X start
6,
Numerical operation function :
abs(x): absolute value ;divmod(x,y): Shang Yu ;pow(x,y,z): Power congruence ((x**y)%z) ;round(x,d): rounding d position
;max/min ; int(x) /float(x) /complex(x)
7,
math library :
constant :math.pi ;math.fabs(x): absolute value ;math.fmod(x,y):x%y
;math.ceil(x): Round up , Return not less than x The smallest integer of ;math.floor(x): Round down , Return not greater than x Maximum integer of
;math.modf(x): return x The decimal and integral parts of ;math.trunc(x): return x Integral part of
8,
Floating Point Types :0.1 + 0.2 Not equal to 0.3 , Floating point numbers have small endings . See if it's equivalent to using it round() Function to help remove small endings .
9, Mixed operation between types :
integer -> Floating point number -> complex
10, Boolean data type (bool) Contains two values ->True( really –1) Or fake (False–0).
If the result of the expression is numeric 0, Empty string (“”), Kong Yuanzu (), Empty list [], Empty dictionary {}, The Boolean value is false( false ), Otherwise true( really ).
11, Logical operators :and,or,not
a and b be equal to a if not a else b ; a or b be equal to a if a else b.
not I will definitely return true or false;and and or not always .
12, Operation priority ( From high to low )
**( index )> +x.-x( Sign )> *./.%( ride . except . Surplus )> +. -( plus . reduce )> &( And )> ^( or )> \( wrong )> Compare size > not( wrong )>
and( And )>or( or )> lambda expression
13, Sequential data
(1) Index of sequence s[i]: If index subscript is out of bounds , cause IndexError; If index subscript is not an integer , cause TypeError.
(2) Slice of sequence ( Intercept sequence s Part of ): Look at the head and ignore the tail .
(3) Addition of sequences :x + y: Connecting two sequences ; Multiplication of sequences ( copy ):x * n: copy n subsequence x ;
(4) Judge substring :x in s : return True/False ; s.count(x): return x stay s Number of occurrences in ;
s.index(x,i,j): return x stay s( Range [i,j]) The first occurrence of the index position in .
(5) Sequence ordering :sorted(s,
key=None,reverse=False).reverse by false It's in ascending order , by true Time is in reverse order . The return result is a list .
(6) Unpacking assignment of sequences : When the number of variables is equal to the length of the sequence , One to one correspondence assignment . as a,b = (1,2) Namely a = 1,b = 2. Inequality leads to inequality ValueError. Or use
variable ( Assign multiple values to a variable as a whole ) Or use temporary variables ‘_’
14, String type
* Compare characters ASCII The size of the code value : Space < number < capital < Lowercase letters
* Unicode Variable character :chr(u) ; Character change Unicode:ord(x)
* format() Method format control :
(1) groove { Serial number } Use of
(2){ Parameter serial number : Format control tag }, Format control tags include : fill , alignment ( Separately <,>,^ It means left , Align right and center ), width , accuracy , type (b= Binary ,c=Unicode,d= decimal system ,o= octal number system ,xX= hexadecimal ).
* Type judgment of string :
str.isdigit() Are all numbers (0-9);str.isalpha() Are all letters ;str.isal
num() Are all numbers or letters ;str.isspace() Is it blank ( Space , Tab , Line breaks, etc );str.isprintable() Is it printable ( Spaces and nothing can be printed );str.isidentifier() Whether the identifier definition rules are met ( Start with a letter or underline , Numbers only , Letters and underscores )
* toggle case :str.capitaiize(): Convert first letter to uppercase , The rest are in lowercase ;str.title() Capitalize each word .
* alignment : Center str.center( length , Fillings ) ; Align left :ljust ; Align right :rjust.
fill :str.zfill( length ) Right aligned , Front fill 0. If str There is a sign before , The sign is also the length , Fill after sign .
remove : Left and right :str.strip( character chars) ; left :str.lstrip() ; right ;rstrip()
* Search of string :find and index
str.find(s): Find from left to right str Does it contain s, If yes, return to the first appearance s Index location for , Otherwise, return -1
str.index(x): From left to right to find if there are x, If yes, the first index position is returned , If not, throw it out ValueError
str.rfind() and str.rindex() It's right to left .
* Substitution of strings :S.replace(old,new,count). take S In old Replace with new, If given count, Replace only the previous count individual old Substring .
* split / division :
S.split( Separator sep, Segmentation times maxsplit), maxsplit =
-1 Or not specified , Searches the entire string from left to right .S.rsplit() It's from right to left . Generate list .
S.partition(sep),S.rpartition(sep)( Search from right to left ). search S Substrings in sep, And from the first sep Division , Returns a string containing three elements
tuple
-->(sep The part on the left ,sep,sep The section on the right ). If the search fails sep, Two elements in the return are empty ,partition Yes, the last two elements are empty ,rpartition Yes, the first two are empty .
* Connection combination :S.join( String object ). When the object is a string dictionary , The result is a key connection .
15, List type
* list list It's a variable object , Then adding, deleting, modifying and checking will not change its function id. except list.copy().
* method :
(1) add to :
list.appand(x): Put the element x Add to the end of the list ;
list.extend(L): List L All elements in the list are added to the end of the list ;
list.insert(index,x): Specify the location in the list index Add element at x;
(2) delete :
list.remove(x): Delete the first element in the list x;
list.pop(kediedai[index]): Delete and return the element at the specified location ( It can be understood as digging out ),list If it's empty, throw it IndexError abnormal ;
list.clear(): Delete all elements in the list , But keep list objects .
(3) sort :
list.reverse(): Reverse order ;
list.sort(): sort ( Positive or negative );
(4) other :
list.index(x): The return value is x First time subscript ;
list.count(x): return x Total number of occurrences of ;
list.copy() : Returns a shallow copy of a list object . Very severe !! It can change the direction of the list ID!
** Shallow copy —— Copy only one layer .** If the copy object has only one layer , So the same b = a[:], Two variables are independent of each other . But if the copy object has only one layer , It will have an impact , It's going to change .( See the example for details )
!! List derivation :
[ New element expression for Temporary variable in Iteratable object if Conditional expression ]
16, Collection type
There is no order for the elements in the collection , And do not repeat . aggregate set It's variable , Use curly braces .
however {} Represents an empty dictionary ;set() Represents an empty collection , use set() When creating a collection , The elements are disassembled one by one , as ’hello’ become ’h’,‘e’,‘l’,‘l’,‘o’.
The elements in the collection are fixed data types : integer , Floating point number , character string , Tuple, etc . Non mutable list , Dictionaries , aggregate .
Use collections to filter out duplicate elements .
4 Two basic operations : hand over (&), and (|), difference (-), repair (^)
S.add() ;S.clear() ;S.copy() ; S.remove() ;len(S) ;x (not)in S ;
**S.pop(): Random return S An element in , If S It is empty , produce KeyError.( distinguish list.pop([index]))
Unique :S.discard(X); If x stay S in , remove x, be not in , No error .
Three main uses : Membership testing , Element de duplication , Delete data item .
17, Dictionary type ( mapping )
{ build (key): value (value)}. Key cannot be repeated , And it's immutable . Variable value . Elements have no order .
Create an empty dictionary :dict() ; Create a dictionary :dict(‘a’=1,‘b’=2)/dict(‘a’:1,‘b’:2)/dict((‘a’,1),(‘b’,2))
Find value :Dict[key] ; Modify key value :dict[key] = new_value ; Add new key value :dict[new_key] = new_value .
D.keys(): Returns a list of all keys , as dict_keys([‘a’, ‘b’, ‘c’]);
D.values(): Returns a list of all values , as dict_values([1, 2, 3]);
D.items(): Returns a list of all key value pairs , as dict_items([(‘a’, 1), (‘b’, 2), (‘c’, 3)]);
D.get(key,v): If the key exists, the corresponding value will be returned , Otherwise, return None( Customized v Time , return v Content of );
D.pop(key.value): If the key exists, the corresponding value will be returned , Delete key value pairs at the same time , Otherwise, return None;
D.popitem(): Randomly take out a key value pair , In tuples (key,value) Formal return ;
D.setdefault(k,v): If the key k existence , Return the corresponding value , Otherwise, add the project k = v,v Default to None;
D.update(dict): Update or add key value pairs ;
D.clear(): Delete all key value pairs ;
del.D[key]: delete key Corresponding key value pair . If key non-existent , Then throw it out KeyError. ergodic :
for Variable name in Dictionary name :
18, Variable and immutable ( About values )
variable : list ( Order ), aggregate ( disorder ), Dictionaries ( disorder )
Immutable : character string ( Order ), tuple ( Order )
Python Value based memory management , give an example :a=[1,2,3],b=[1,2,3],a==b establish .
however id(a) And id(b) Unequal ,id(a[0])==id(b[0]) establish . Sum up is about the value of the equal
What is variable ? That is, the value is variable , but id It's fixed . For example, variable lists , Modify list L The value of an element in , list L Of id It's the same .
Whether variable or immutable sequence types :
(1) Fragmentation must produce new sequences ;
(2)“+” The number is to the right of the equal sign (L=L+[i]), There must be a new sequence . The new sequence address is then assigned to the variable to the left of the equal sign .( The original list will be copied every time ,L Point to new list , And add new elements to the new list )
The three methods of list addition are summarized :
(1)L=L+[i] In each execution, the original list will be copied once ,L Point to new list , And add new elements to the new list .
(2)L.append(i) Just add the new element directly to the original list , No new list will be generated .
(3)L+=[i] The implementation effect and quality of the project L.append(i) similar , You can also add elements directly to the original list , The original list will not be copied .
b = a VS b = a[:]
b = a Time ,b Just follow a change , also a And b Of id equally .b =
a[:] Time ,b And a It's an independent whole ,id It's different , It just points to the same value . yes a Make changes ( Add, delete, change and search ), yes b No impact .
19, Three basic structures of program :
Sequential structure ,· Branching structure (if-else,elif),· Cyclic structure ( ergodic :for…in, condition :while. Cycle control :break/continue).
Outlier handling :try-except.
Two branch structure simple grammar : expression 1 if condition else expression 2
Cycle structure is divided into ergodic cycle (for) And infinite loop (while):
Ergodic loop :for Cyclic variable in Ergodic structure : Statement block ( Extract elements one by one from traversal structure , Put it in a loop variable , Execute the statement block once for each extracted element .)
Infinite cycle :while condition : Statement block . The judgment condition is True It's just a cycle , by false The end of the ring , Implementation and while Subsequent statements indented at the same level .
break Used to end the current loop , If there's a two-layer loop ,break Used to jump out of the innermost layer for or while loop , After leaving the loop, the program continues to execute from the post loop code ;
continue Used to end the current cycle , That is, jump out of the loop body of the following statement has not been executed , But don't jump out of the current cycle .
When there is an input request , Abnormal value processing can be used try:except:
20, function
(1) Formal parameter and actual parameter : The parameters to define a function are formal parameters , The arguments to the function are arguments .
(2) Method of parameter transfer : Location parameter , Default value parameter , Keyword parameters , Named keyword parameters ...
Location parameter : Pass parameter values in positional order , Position parameter should be before all parameters , This is the first parameter ;
Keyword parameters : Keyword parameter is calling function , Specifies the variable name of the formal parameter when the argument is passed in . Keywords do not follow the correspondence of positions . The order of parameters can be adjusted arbitrarily . Keyword delivery can be mixed with location delivery . But the positional parameter should precede the keyword parameter . give an example :def
hello(name,age = 11,gender = ‘F’):(age = 11,gender = 'F’ It's a keyword parameter )
. give an example :def hello(name,age = 11,gender = ‘F’):(age = 11,gender = 'F’ It's a keyword parameter )
Default value parameter : A value has been given when the parameter is defined , General parameters are immutable objects ,( If it is a variable empty list , It can be used to set position parameters );
Variable quantity parameter :*args,**kw
With an asterisk * Variable parameters of can only appear after the parameter list . On call ,* Arguments are passed to the function as tuple types .( as : def func(*args): ->
func(10,20))
With double star (**) Parameters of , Parameter values must be specified when using , use key=value This form , Can only appear at the end of the parameter list . On call ,**kw The latter parameters are treated as dictionary types
Pass to a function .( as :def func(**kw): -> func(a=10,b=20))
Forcing named parameters : The parameter has an asterisk or an asterisk (def f(*c or *,a,b,c)), Force command parameters *c The meaning of is that the parameters after it must be called with real names , That is, it must be used a = …
, b = … To call , You can't just write values .
Python There are only functions in , Function has a return value ,** without return, Default return None.**return When multiple values are returned , Multiple values are saved as tuples .
21, compare
(1)list.sort() And the overall situation sorted()
list.sort(key = None,reverse = False) Is the list built-in sort method .
But the return value is None(x.sort() Results ,print(x.sort()),x = x.sort() after x All the results are the same None
), Only when words say “ Execution statement x.sort(),x The value of is ”,x.sort() The result of action , You need to print the affected list to view the results .true It's in reverse order ,false It's a positive order .
sorted():Python Built in method . Return to new list .
(2)list.reverse() and reversed()
list.reverse() What is returned is None, The result of its action , You need to print the affected list to view the results .
reversed(): Built in method . after reversed() After effect , Return is a bar sequence value through the inverted iterator
, therefore , Need to traverse or list,tuple or next() method , To get the value after the action .
(3) Search of string :find and index
str.find(s): Find from left to right str Does it contain s, If yes, return to the first appearance s Index location for , Otherwise, return -1
str.index(x): From left to right to find if there are x, If yes, the first index position is returned , If not, throw it out ValueError
str.rfind() and str.rindex() It's right to left .
22, Scope of function variable
(1) local variable , global variable ,global
global: Used to modify the value of a global variable directly in a function .
(2) Nested Function
The scope of an embedded function is limited to the body of the function in which it is located . If you want to modify the value of the local variable in the external function in the internal function , use nonlocal keyword .
Technology