Python Learning Summary

Source: Internet
Author: User
Tags assert iterable local time serialization

As
Update Time: 2017.12.30

Email:[email protected]

Description: Because of more content, will continue to update the XXX learning summary;

1.python Introduction:

2.python Interpreter

3.python Foundation:

1. Data types, variables, strings, encodings
2.list,tuple,set,dict,
3. Condition judgment, circulation
4. Functions and parameters, recursive functions, packet functions, anonymous functions, partial functions
5. Slices, iterations, list generation, generator
6. Functional programming, high-order function map,reduce,filter,zip,sorted
7. Adorner, module,
8. Error handling, commissioning, testing
9.IO file read/write
10. Serialization, Process, multithreading
11. Regular Expressions
12. Common built-in modules
13. Common Web Framework Flask,django

-----------------------------------------------------------------------------

1.python Introduction:

1.python is called glue language, meaning is omnipotent, where can use Python to develop, this shows that Python is now very fire, especially now artificial intelligence, machine learning compared to fire, good people are learning python.

2.Python is a programming language written by the famous "Uncle Turtle" Guido van Rossum during Christmas 1989 to send a boring Christmas. There are currently python2.* and python3.* used in industry,

If you start learning python now, it is recommended to start with pyton3.*, since python2.* is not available for support and updates from 2020 onwards.

2.python Interpreter

To run the code, a text file with the extension of. PY will need the Python interpreter to execute the. py file.

The IDE currently developed is: Pychart,sublime text2/sublime Text3

3.python Foundation:

1. Data types, variables, strings, encodings

Int,double,str,bool,none, constants

a=2

b=2.12

c= ' Test '

D= True

E=none

pai=3.1415927

Things to keep in mind Python's data type is not defined, and the interpreter automatically matches the data type based on the type of data;

Python supports a variety of data types, and within a computer, you can think of any data as an "object."

Ord (' A ') #print65

char (#print B)
2.list,tuple,set,dict,

Directly above the bar, the most intuitive:

-------------List--------------------

List0=[]

list1=[1,2,3,4]

List2=[' A ', ' B ', ' C ']

list3=[1,2.12, ' A ', List1]

Type (LIST3)

Print (list3[0] #index get value

List4 = List1 + list2

LIST5 = List1 * 3

Len (LIST5)

For I in LIST5:

Print (i)

List6 = 2 in List5

Del List6[1]

Del List6

Max (LIST6)

Min (LIST6)

List5[1:4]

List5[1:4:2]

List5[2:]

List5[:4]

List5=[' A ', ' B '] #updated value

List5.append (), List5.count (' a '), List5.extend (Val), List5.index (obj), List.instert (Index,obj),

List5.pop (' a ')

List.remove (Valu)

Del list[' Valu ']

----------Tuple-------------------------

Tuple1= ()

Tuple2= (a)

Tuple function: Index, slice, join, copy, loop on inner element, find out whether an element exists, delete tuple, return maximum minimum value reference list, not listed

Tuples and lists convert each other

Tuple1= (a)

List1=[' A ', ' B ', ' C ']

Tuple2=tuple (List1)

List2=list (Tuple1)

LIST3 = [n+m for n. ' abc ' for M in ' ABC ']

Tuple Package Unpacking:

tuple4=1,2,3,4

A,b,c,d=tuple4

----------------------dict Funciton----------------------------------------

dict1={}

Dict2={' A ': 1, ' B ': 2, ' C ': 3}

Dict3=dict ([' A ', 10],[' B ', 20])

Dict4 = Dict ((' A ', ten), (' B ', 20)))

Dict5=dict (A=10,B=20)

DICT6=[1:10,2:20]

Dict1[' a ']

Dict7 = ' A ' in Dict1 #true or False

Dict1.keys ()

Dict1.values ()

Dict1.items ()

Dict1.clear ()

Dict1.get (Key,default=none)

Dict1.pop (Key)

Dict1.setdefault (Key,default=none)

Dict1.update (newdict)

Dict8=copy.deepcopy (DICT2)

-------------------------Set----------------------------------------------------------------------

Non-repeating unordered set {}, cannot use list, dictionary as element

set0=set{}

Set1 ={1,2,3,4,5}

set2={1,2.33, ' Test ', (+)}

Set1.add (x)

Set9 =set1.updte (Set2)

Set1.pop () #执行一次按顺序删除一个元素

Set1.remove (x)

Set1.discard (x)

Set1.clear ()

Set1.intersection (Set2)

Set1.untion (Set2)

Set1.diffrence (Set2)

Set1.issubset (Set2)


3. Condition judgment, circulation

If a<10:

Elif a<20:

Else

For x in List1:


4. Functions and parameters, recursive functions, packet functions, anonymous functions, partial functions

Def def1 ():

Def Def2 (a)

def def3 (a,b=2,c= ' Shenzhen ')

def DEF4 (a,*b,**kw):

def def5 (a,b,*,city,name) #命名关键字参数, must be separated by *, followed by the name of the keyword parameter

Recursive functions: Functions call other functions inside, call themselves also;

anonymous function: f1= lambda x:x+x

5. Slices, iterations, list generation, generator

list1=[1,2,3,4,5,6]

List2=list1[1:4]

Iteration: A set that can be traversed is called an iteration;

For K in Dict:

Print (k)

Python's built-in frontal function enumerate can change the list to an index-element pair so that the for loop iteration can be used;

For x, y in enumerate ([' A ', ' B ', ' C '):

Print (x, y)

List1=[x for x in range (10)]

Generator: i = (x for x in range) #generator yioid

Next (i)

All objects that can be used for a for loop are iterable types;
All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;
Collection data types such as list, Dict, str, and so on are iterable but not iterator, but a iterator object can be obtained through the ITER () function.

6. Functional programming, high-order functions, map,reduce,filter,zip,sorted

Functional programming: Process-oriented programming, the task is divided into a number of small tasks, each small task by a function to complete the function;

Higher order function: A function that allows an accepted function as a parameter is called a higher order function;

Map: Takes a function, a sequence, and passes the passed function arguments on each element of the sequence and returns a list

Map (fn[1,2,3,4]

Reduce: The function sequentially acts on each of the successive 2 elements and returns a result;

Reduce (fn,[1,2,3,4]

Filter (): accepts a function, a sequence, passes the passed function parameter on each element of the sequence and, depending on the ture or false returned, decides whether to discard the object to return the result set

Sorted (): Advanced functions, which accept functions and sequences, function on each sequence element;
7. Adorner, module,
 

def now ():
f = Now
f.__name__ #now

  The way the adorner dynamically adds functionality during code runs, called an "adorner" (Decorator).  

Decorator is a higher-order function that returns a function


8. Error handling, commissioning, testing

Error Handling

Try

Print (' Try ... ')

Except Zerodivisionerror as E: #更多错误处理类可以网上查询: Ioerror,valueerror,

Print (' except:: ', E)

Finally

Print (' Finllay ... ')

Debug

1. Print () The variables that are likely to be problematic to look at;

2. Any place where print () is used to assist in viewing can be substituted with an assertion (assert), and if the assertion fails, the Assert statement itself throws Assertionerror:

3. Replace print () with logging is the 3rd way, and assert ratio, logging will not throw an error, and can be output to the file Logging.info (' n =%d '% n)

Import logging
Logging.basicconfig (Level=logging.info)

Logging benefits, it allows you to specify the level of logging information, there are several levels debug,info,warning,error and so on, when we specify Level=info, Logging.debug will not work

The 4th Way is to launch the Python debugger pdb, let the program run in a single step, you can view the running state at any time

At present, the better Python IDE has pycharm, but it seems to charge, but online can find the registration code ~ ~

So many debugging methods, although debugging with the IDE is more convenient, but in the end you will find that logging is the ultimate weapon.

Test:

Unit testing is a test that is used to verify correctness of a module, a function, or a class.


9.IO file read/write

f = open ('/users/michael/test.txt ', ' R ') # ' R ' denotes

F.read ()

F.close ()

ReadLines () reads all the contents one at a time and returns the list by row
ReadLine () can read a line of content every time
Read (size) method, reading the contents of a maximum size byte at a time
Read () reads the entire contents of the file at once

For line in F.readlines ():
Print (Line.strip ()) # Erase the end of ' \ n '

To read binary files, compare slices, videos, etc., open files with ' RB ' mode, ' W ' to write files
f = open ('/users/michael/test.jpg ', ' RB ')
f = open ('/users/michael/gbk.txt ', ' R ', encoding= ' GBK ')


10. Serialization, Process, multithreading

Python language-specific serialization modules are pickle, but if you want to make serialization more generic and Web-compliant, you can use a JSON module.
The dumps () and loads () functions of the JSON module are examples of well-defined interfaces.

Pickling:

Pickle.dumps (d) # str to bites
Pickle.loads () method deserializes an object @ bites to str
To deserialize JSON into a Python object, use the loads () or the corresponding load () method
Print (Json.dumps (s, Default=lambda obj:obj.__dict__)) #把任意class的实例变为dict

The process of changing a variable from memory to a storage or transfer is called serialization, called pickling in Python
After serialization, the serialized content can be written to disk or transferred over the network to another machine.

Unpickling:
In turn, re-reading the variable contents from the serialized object into memory is called deserialization, i.e. unpickling.

Import Pickle
>>> d = dict (name= ' Bob ', age=20, score=88)
>>> Pickle.dumps (d)

The Pickle.dumps () method serializes any object into a bytes and then writes the bytes to the file. Or use another method Pickle.dump () to serialize the object directly and write to a file-like. Object
>>> f = open (' Dump.txt ', ' WB ')
>>> Pickle.dump (d, F)
>>> F.close ()

Multi-process:

Python supports both multi-process and multi-threaded

A thread is the smallest execution unit, and a process consists of at least one thread. How to schedule processes and threads, completely determined by the operating system, the program itself can not decide when to execute, how long to execute


11. Regular expressions, re-modules

[0-9a-za-z\_] can match a number, letter or underline;
? [0-9a-za-z\_]+ can match a string consisting of at least one number, letter, or underscore, such as ' A100 ', ' 0_z ', ' Py3000 ', etc.;

[A-za-z\_] [0-9a-za-z\_]* can be matched by a letter or underscore, followed by a string consisting of a number, letter, or underscore, which is a valid Python variable;
? [A-za-z\_] [0-9a-za-z\_] {0, 19} More precisely restricts the length of a variable to 1-20 characters (preceding 1 characters + 19 characters later)

Re.split (R ' \s+ ', ' a B C ')

The regular expression is very powerful, here just mention a little bit, specific can be online query.


12. Common built-in modules

1.datetime is the standard library for Python to process dates and times

1. Get the current date and time
2. Get the specified date and time
3.datetime conversion to Timestamp
4.timestamp Conversion to DateTime
5.STR Conversion to DateTime
6.datetime to Str
7.datetime plus minus
8. local time converted to UTC time
9. Time Zone Conversion
From datetime import datetime
now = DateTime.Now () # Gets the current datetime
DateTime (2015, 4, 19, 12, 20)
Cday = Datetime.strptime (' 2015-6-1 18:19:59 ', '%y-%m-%d%h:%m:%s ')
Print (Now.strftime ('%a,%b%d%h:%m '))
Now + Timedelta (hours=10)
Utc_dt = Datetime.utcnow (). Replace (TZINFO=TIMEZONE.UTC)

2.urllib
3.HTMLparser
4.XML
5.base64


13. Common Python web framework

Flask (small), used, for small projects;

Django (Large):

Web this piece of content more, specific people can find learning on the Internet, here is not explained.

-----------------------------End------------------------------------

Reference books:

Book "python3-Liaoche", "Stupid Way to learn Python (third edition)"

Python Learning Summary

As

Learning Time:---2017.03
Email:[email protected]

Python Learning Summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.