<> Text writing

.title() Initial capital
.upper() All capitals
.lower() All lowercase
\n Space
\t Line feed

<> List element processing

.lstrip() Clear the white space at the beginning of the string
.rstrip() Clear the white space at the end of the string
.strip() Clears all extra white space in the string
** Two multiplication signs represent the power operation
str() character string
[] column
print( variable [0]) The first element
print( variable [-1]) Access the last element of the list and so on
.append() Add the element to the end of the list ( You can create blank columns and add them )
del variable [] Delete element ( Never use it again )
.pop() Pop up end element pop(0) Pop up the first element ( Keep deleted elements )
.remove(‘ value ’) Find the element based on the value and delete it Delete value can be used
.insert(0,‘ element ’) Add element to beginning ( Add elements to any location )
.sort() Sort in alphabetical order ( Permanent )
.sort(reverse=True) In reverse alphabetical order ( Permanent )
sorted( variable ) In alphabetical order But the original sequence was not changed
sorted( variable ,reverse=True) In reverse alphabetical order But the original sequence was not changed
.reverse() Inverts the arrangement of list elements ( It's not about alphabetic order )
len() Get list length ( The calculated element is derived from the 1 The beginning )

<>for sentence :

for Storage variables in Defining variables :
print( Storage variables )
for Code that does not indent after the loop is executed only once , It will not be repeated
for Storage variables in range(1,5) The output is 1,2,3,4
list(range(1,5)) Digital to list , The output is [1,2,3,4]
Specified Steps range(2,11,2) The last one is the increase from 2 Start counting 11
min() minimum
max() maximum
sum() Sum up
for A simple way to write :
variable =[y**2 for y in range(1,5)] Seek in turn 1 reach 4 Square of
section ( For sequence , Serial number from 0 start )
print( variable [0:3]) The output is three elements 0,1,2
( [:3]) from 0 Start to the third
( [2:]) From the third element to the last element
( [-3:]) The last three elements
( [:]) All elements
tuple :
( Immutable list , use () express , You can only modify values by modifying tuple variables )
( Immutable : Values that cannot be modified )
Indent format : empty 4 Spaces Better not exceed 79 Characters

<>if sentence :

Condition test : The core is a value of True or False Expression for
format :== Two equal signs are inspection , The meaning of asking questions
Case as a comparison factor , But it's the element .title() The original variable value will not be changed
!= Not equal to ( More efficient )
< less than > greater than <= Less than or equal to >= Greater than or equal to
Check multiple conditions : Using logical relations
and( Only when they are satisfied can they pass )
or( Any one of them can be satisfied )
in For specific value checking ( No colons It doesn't match if Time )
not in ( collocation if Time plus colon )
Boolean expression : Another name for conditional testing , Boolean values are used to record conditions
example :game_active=True can_edit=False
ordinary if Circulation and for identical , Can follow any number of lines of code
if-else Structure should be colon
if-elif-else structure ( It can be used in many situations , When the final test condition is known, it can be omitted else,
But the structure is suitable for only one condition is satisfied )
if Under special conditions , There may be multiple conditions for True In the case of

<> Dictionaries

Dictionaries ={‘ Storage variables 1’:’’, Storage variables 2:’’}
print( Dictionaries [‘ Storage variables ’]
Add key _ Value pair : Dictionaries [‘ Storage variables 3’]=?
be careful :python Don't care about the key _ The order in which value pairs are added , Only the relationship between key and value is concerned
You can create an empty dictionary , Then add them one by one
Modify value method = The added value overlaps the original value
Delete key _ yes :del Dictionaries [‘ element ’]
A dictionary of similar objects ( Many objects )
Dictionaries ={
Sentence one
Sentence two
Sentence three
}
longer print Statement line
print( First sentence +
The second sentence
The third sentence )
Traverse dictionary (for loop )
1. All keys _ yes :
for new_1,new_2 in Dictionaries ,items():
print(“new_1:”+new_1)
print(“new_2:”+new_2)
2. Traversal key :.keys()
3. Ergodic value :.values()
4. Sort order :sorted( variable .keys() perhaps values.())
5. Eliminate duplicate items , Using collections set( variable ) Same sort
6. nesting : Automatic generation of random code , use range() Realized py
7.for Cyclic addition if Circularly generated random variables
8. List in dictionary
9. Dictionary set

<>While Circulation and input

1. variable =input(’’) The property of the variable is a string
2. operator :+= Store the string in the variable and add a string at the end
3.int() Converts a string to a number
4.% Modulo operator Divide two numbers and return the remainder a%b
5. Judging odd even numbers (if else %)
6. Basic cycle utilize +=
7. User opt out , You need to define a blank variable in the middle
take print Put in if behind , Solve the problem of printing out unnecessary variables
8. sign : Define a variable , It is used to judge whether the whole program is active or not
9. The significance of logo : Give Way while Just judge that the tag value of the program is True or False
[ Game crash caused by multiple events ]
10. variable =True Make the program active initially use while and if Do a cycle
11.break Jump out of the loop For python Any cycle
12.continue It's like skipping
13.Ctrl+c To terminate an infinite cycle It's OK to turn it off
14.while and for The difference between :
for The list should not be modified in the loop ,
while The object can be modified while traversing the list
15. Delete all list elements for a specific value : stay while In the loop, the variables .remove(‘ Specific value ’)
16. User input to fill in the dictionary

<> function

def Formal parameter ( Actual parameters ):
[ Passing arguments :]
1. Positional argument : Sequential join of formal parameter and actual parameter based on actual parameter ( The positions must correspond one by one )
2. Keyword argument : Specify the actual parameter corresponding to the formal parameter in brackets
3. Formal parameters can be set to default values ( It is recommended to use less )
4. Return value : The value returned by the function
5. Defining a formal parameter as an empty string makes it optional ( Store the name in two words and three words , Put more words in the back )
6.python Understand non empty strings as True
7. Delivery list : Function can directly access the content
8. Modify the list in the function : Used to handle tasks that are executed too many times
9.functiong_name(list_name[:])# Create a copy Forbidden function modification list
10. Formal parameter # Create an empty tuple named formal parameter , Takes any argument and encapsulates it in a tuple
11. Accept different types of arguments , The formal parameters of the plus sign are placed at the end
12.** Formal parameter # Create an empty dictionary , Install all the keys _ Value pair
[import]
1.import Template name # Import function template
2. Template name . Function name () # Call any function of template
3.from Template import Function name # Import specific functions
4.from Template import Function name _1, Function name _2, Function name _3
[as] assign an alias
1.from Template import Function name as New name # To assign an alias to a function
2.import Template as New name # Assigning an alias to a template
3.form Template import * # Import all functions ( Not recommended ) Call function directly , Template name without prefix
4. When a default value is specified for a formal parameter , There should be no spaces around the equal sign , The key value is the same as the real parameter

<> class

1. Creating objects based on classes is called instantiation
2. Capitalized names refer to classes
3.__init __ method ( Remember two underscores on each side )
4. Accessing a variable through an instance is called a property
5. The period notation is demonstrated python How to know the value of a property
6. Class can create multiple instances
7. Each property of a class must have an initial value , Even if it is 0 Or empty characters
8. Modify the value of a property :① Modify the value of the property directly ② Modify the value of a property through a method ③ Incrementing the value of a property through a method
9.python A standard library is a set of templates
10. Class coding style : Nomenclature of hump ( Capitalize the class name , Don't underline , Both instance name and template are lowercase , Underline between words )
[ inherit ]
1. When defining subclasses , The name of the parent class must be specified in parentheses
2.super(). It's a special function , help python Associate a parent class with a child class
3. A parent is also called a ‘ Superclass ’(superclass)
4.2.7 In version You need to put a parenthesis in the parent class object super Function requires two time arguments in parentheses : Subclass name , object self
5. Use instance as property , Create a new class , No classes are inherited
[ Import class ]
1.from file name import class ( recommend )
2. Import entire template ( Import with function ) Template name . Class name
3. Import template all classes from module_name import * ( Not recommended )
4. Import another template from the template Import the parent class from the parent class template in the template of the child class

<> file

1.with open(‘ file name ’) as file_object:
2.open() open close() close .read() read .readlines() Read each line , And stored in a list
3.rstrip() Delete the empty line after the file
4. File path lookup
(1)Linux: with open(‘text_files/filename.txt’) as file_object:
(2)Windows: with open(‘text_files\filename.txt’) as file_object:
5. Absolute path lookup
(1)Linux OSX :file_path =
‘/home/ehmatthes/other_files/text_files/filename.txt’
with open(file_path) as file_object:
(2)Windows:file_path =
r’C:\Users\ehmatthes\other_files\text_files\filename.txt’
with open(file_path) as file_object:
be careful : Backslash in python Is treated as an escape token Make sure it's safe , Should be preceded by a single quotation mark at the beginning r
6. Read line by line :for loop for line in file_object:
7.python read file , Read all text as a string
8. write file :open() Two arguments are provided The first argument opens the file On the second argument :
'r’ Read mode 'w’ Write mode 'a’ Additional mode ‘r+’ Read and write mode
9.python Text can only be written as a string
10. Additional mode does not override the original content , The write file is added to the end of the file

<> abnormal

1.try_except Code block There must be one of the two
2. Analyze text : split() Create a word from a string [ list ]
3.pass sentence Give Way python Don't do anything Put in except in

<> Store data

1.json format (JavaScript Object Notation)
2.json.dump() Store data json.load() Read data
3.json.dump() Take two arguments : Data to store , Storage data file object
4. restructure : The code is divided into a series of functions to complete the specific work

<> Test code

1.python Template of standard library unittest Provides code testing tools
2. unit testing : Used to verify that one aspect of the function is OK
3. test case : A set of unit tests
4. Full coverage testing : A complete set of unit tests
5. Template unittest: assert methods ( Verify that the results are as expected )
6.unittset.TestCase Assertion methods in classes :
assertEqual(a,b) verify a==b
assertNotEqual(a,b) verify a!=b
assertTrue(x) verify x by True
assertFalse(x) verify x by False
assertIn(item,list) verify item stay list in
assertNotIn(item,list) verify item be not in list in
7.setUp() # First, run the method , Rerun test Start with
8. The period represents the passing of the test ,E On behalf of the test raised an error ,F The delegate test caused the assertion to fail

Technology