Basic knowledge of Python

Basic knowledge of Python

1. List

Points to note:
1. The elements in the list can be of different types
2. The elements in the list can be different lists
3. Read the list in a list list[3][1]
4.index returns the index of list.index Value
5. You can modify the elements of the list object
6.list.insert(index,Value) Insert at a certain index position
7.del list[index] Delete the index value specified by the
list 8. List containment a="PY" n= [1,2,3,4]
print([(x,y) for x in a for y in n])
9. List operation symbol
+ combination list * repeat list
10. List function len() /max() /min()
11.list() Replace the meta-assembly with a list
12.sum function
13.print(dir[]) Display all methods
14.extend() Combine the list and "+" function similar to
15.pop( index) Delete the index value and the corresponding index
16.remove(Vale) Delete the value in the list

Two. Tuples

1. The tuple has only one element and must be added after the element
2. The object of the tuple cannot be modified
3. The object of the tuple can be indexed
4. The + sign combination tuple
5. The element cannot be deleted del() Delete the entire tuple
6. The general function len() max() min() sum()
7. The list()/tuple() function replaces the list and tuple with each other

Three. Dictionary

1.dic={'name':'Jack','Sex':'Male','ID':1212}
2. Return the value by key value
3. It is not allowed to have the same key value twice, and the same key is Assignment twice, the latter is overwritten
4. The elements in the dictionary can be modified
5. print(dir({})) The method to display all dictionaries
6.get(K[d]) There is K dic.get(" name”)
7.Items() dict.items() Convert the dictionary into an
outputable list 8.keys() Return all key values ​​and generate a list
9.valus() Return all values ​​and generate a list
10.Setdefault( k, d) Add a dictionary element, if there is one, do not add
11.popitem() Delete the first element in the dictionary
12.update({'Street':"Xingdou Garden Room 701"}) Add to the dictionary

Four. Escape characters

Insert picture description here

Five. String

1.captitalize capitalize the first word of a character, and all lowercase after it
2.upper capitalize all characters
3.lower all lowercase
characters
4.title capitalize the first letter of all words of the character 5.swapcase change all words in the string to small Big, big and small
6.Isalnum() A string of letters and numbers
7.Isapha() A string of letters and Chinese characters
8.isdigit() A string of numbers only
9.count() Calculate the length of the string
10.find() Find the index value of the letter
11.index() is consistent with the find() function, and an error is reported
if it is not found 12.join() single element accumulation
13.replace() print str.replace(old, new, 3) ; Here 3 means no more than 3 replacements
14 max(), min() return the corresponding ASII code

Coding style introduction:
class name: camel case and acronym: HTTPWriter is better than HttpWriter.
Variable name: lower_with_underscores.
Method name and function name: lower_with_underscores.
Module name: lower_with_underscores.py. (But the name without underscore is better!)
Constant name: UPPER_WITH_UNDERSCORES.
Pre-compiled regular expression: name_re.
For details, please visit: https://www.cnblogs.com/zhizhan/p/5546539.html

String formatting
Insert picture description here

Six. Operator

Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here
Liezi:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0

c = a & b; # 12 = 0000 1100
print "The value of 1-c is:", c

c = a | b; # 61 = 0011 1101
print "The value of 2-c is:", c

c = a ^ b; # 49 = 0011 0001
print “The value of 3-c is:”, c

c = ~a; # -61 = 1100 0011
print "The value of 4-c is:", c

c = a << 2; # 240 = 1111 0000
print "5-the value of c is:", c

c = a >> 2; # 15 = 0000 1111

Insert picture description here
Insert picture description here

Seven. Conditional judgment

  1. if …else…
  2. if… elif… elif…
  3. Ternary expression

8. Loop

1.while 2.for
3.break
break out of the loop
4.continue break out of the single loop
5.pass empty statement

Nine. Function

1. Transmission of parameters:

1) Required parameters
2) Keyword parameters
3) Default parameters: When the function is called, if the value of the default parameter is not passed in, it is considered as the default value. The following example will print the default age, if age is not passed in:
4) Variable length parameters: You may need a function that can handle more parameters than it was originally declared. These parameters are called indefinite length parameters, which are different from the above two types of parameters. They are not named
in the declaration, such as:
****def test(*args):#*args: elements in tuples, args: tuples storing data The variable name
print(*args)
def fun( args):# args: the element in the dictionary (only key), args: the variable name of the dictionary storing the data
print(args)
fun(username="Zhang San", age= 18)#{'username':'Zhang San','age': 18}

5). If you want to change the value of a global variable in a function, you must use the keyword global to declare

2.lambda expression

Insert picture description here

3. Closure thought

def sayHI():
print("Hello")
def SayHIs(sayHI):
sayHI()
print("Hello again")

The extension of the closure idea decorator
#The use of decorator
import logging
1. The initial requirement is to pass the function as a parameter to the function to form a closure
def Use_log(fuc):
logging.warn("%s is runing"%fuc. name )
fuc()
def bar():
print('i am a bar')
Use_log(bar)

#2.装饰器的延伸思想
def Use_log(fuc):
def warper(*args,**kwargs):
logging.warn("%s is runing"%fuc.name)
return fuc(*args,**kwargs)
return warper

def bar1():
print(‘i am a bar11’)

bar=Use_log(bar1)
bar()

#3. The evolutionary version of the
decorator def Use_log(fuc):
def warper(*args,**kwargs):
logging.warn("%s is runing"%fuc. name )
return fuc(*args,**kwargs)
return warper

@Use_log
def bar1():
print(‘i am a bar222’)
bar1()

4. Usage of decorator with parameters

def Use_log(leven):
def decorator(func):
def wapper(*args,**kwargs):
if leven==“Main”:
logging.warn("%s is runing"%func.name)
return func(*args,**kwargs)
return wapper
return decorator
@Use_log(leven=‘Main’)
def bar1():
print(‘i am a bar11’)
bar1()

#5. Usage of class decorator Class decorator has the advantages of flexibility, high cohesion, encapsulation, etc.
class FOO(object):
def init (self,func):
self.func=func
def call (self, *args , **kwargs):
print("The position before the record")
self.func()
print('The position after the call')
@FOO
def bar1():
print('i am a bar11')
bar1()

#functools wraps can copy the meta information of the original function to the decorator function, which makes the decorator function have the same meta information as the original function
from functools import wraps
def logged(func):
@wraps(func)
def with_logging(* args,**kwargs):
print("{} was called".format(func. name ))
return func( args,**kwargs)
return with_logging
@logged
def f(X):
return X + X
X

5. Higher-order functions

1.lambda
2.reduce binary operation function from functools in reduce
3.map two parameters, one is a function and the other is a
sequence of numbers 4.filter will filter the sequence, one is a function and the other is a sequence of numbers
#High-order function
def add(x,y ,f):
return f(x)+f(y)
print(add(-5,6,abs)) #anonymous
function lambda expression lambda[arg1]
sum=lambda x,y:x+y
print(sum( 10,20))
def MAX(a,g):
max=a[0]
for i in range(len(a)):
if g:
max=a[i]
return max
a=[1,2,3, 6,6,43,20,99]
print(MAX(a,lambda x,y:x>y))
#reduce is a binary operation function
from functools import reduce
l=[1,2,3,4,5 ]
l1=[7,8,9]
print(reduce(lambda x,y:x+y,l))
print(reduce(lambda x,y:x+y,l,20))
#map function accepts 2 parameters, one is a function and the other is a sequence, map will apply the passed function to each element of the sequence in turn, and return the result as a new list in the format: map(func,seq1[,sq2…] )
print(list(map(lambda x:x+1,l)))
try:
print(list(map(lambda x,y:x+y,l,l1))) #Combine the two arrays
except:
print("there is a error")

#filter function to filter the sequence
print(list(filter(lambda x:x>3,l))) #Skillful use of reduce map filter
5. Decorator
6. Descriptor (understanding too much brain) Control class behavior

#Python functional programming
1. Three major features: Immutable data functions use tail recursion optimization like variables: stac is reused every recursion
2. Mode advantages: concurrency, lazy evaluation, determinism
3. Functional programming technology: lambda map filter reduce pipeline recursing recursive currying higher order function
4. Functional programming logic: such code is describing what to do, not how to do it

6.Python data types

  1. int(x[,base]) convert X to an integer
  2. long(x[,base]) convert X to a long integer
  3. float(x) convert X to a floating point number
  4. complex(real[,imag]) creates a complex number
  5. str(x) convert X to string
  6. repr(x) converts the object X into an expression string
  7. eval(str) is used to calculate a valid Python expression in a string and return an object
  8. tuple(s) converts the sequence S into a tuple
  9. list(s) convert the sequence to a list
  10. set(s) is converted to a variable set
  11. dict(d) creates a dictionary
  12. frozenset(s) is converted to an immutable set
  13. chr(x) Convert an integer to a character and return the ascii code of the corresponding character
  14. unichr(x) converts an integer to a Unicode character
  15. ord(x) converts a character to its integer value and returns the ascii code of the corresponding character
  16. hex(x) converts an integer to a hexadecimal string
  17. oct(x) converts an integer to an octal string

10. Class

1. Encapsulation
2. Inheritance
3. Polymorphism
. Introduction to
object -oriented objects. Objects are instantiations of classes.
Object characteristics: static characteristics/dynamic characteristics.
Static characteristics: the appearance, properties, attributes, etc. of the object.
Dynamic characteristics: function, behavior

11. Program debugging

1. Introduction to
assert function Introduction to assert function
Program debugging

12. File reading and writing

File writing and reading

13. Store data

Json data

14. Built-in exceptions

1.sys module SYS module

15. Handling exceptions

Exception handling

16. Module/Library

Summary of Python modules (common third-party libraries)

17. Regular expressions

Regular expression

18. Random number

random number

19. Iterator

Iterators and generators

Guess you like

Origin blog.csdn.net/Zerogl1996/article/details/113874351