Python Common knowledge points

Source: Internet
Author: User
1. Set basic data Type

A, set set, is an unordered and non-repeating collection of elements

Class set (object): "" "Set (), new empty Set object Set (Iterable), new set object Build an unordered colle  Ction of unique elements. "" "" "Def Add (self, *args, **kwargs): # Real signature Unknown" "" "" "add an element to a set, adding elements this have no E    Ffect if the element is already present. "" "Pass def Clear (self, *args, **kwargs): # Real signature Unknown '" "Remove all elements from the this set. Clear content "" "Pass def copy (self, *args, **kwargs): # Real signature Unknown" "" "" Return a shallow copy of a set. Light copy "" "Pass def difference (self, *args, **kwargs): # Real signature Unknown" "" Return "the difference of the" O " R more sets as a new set.    A is present, and B does not exist (i.e. all elements the is in this set and not the others.)  "" "Pass Def difference_update (self, *args, **kwargs): # Real signature Unknown '" "Remove all elements of another Set from the This set. Remove from current collection and b the same element "" "Pass Def Discard (self, *args, **kwargs): # Real Signature Unknown "" Remove an element from a set if it is a member. If the element is not a member, does nothing. Removes the specified element, does not exist "" "Pass Def intersection (self, *args, **kwargs): # Real signature Unknown" "" Return the Inte Rsection of sets as a new set.    Intersection (i.e. all elements, is in both sets.) "" "Pass Def intersection_update (self, *args, **kwargs): # Real signature Unknown '" "" Update a set with the Inters Ection of itself and another. The intersection and update to a "" "Pass Def Isdisjoint (self, *args, **kwargs): # Real signature Unknown" "" "Return True if the sets ha ve a null intersection. Returns true if there is no intersection, otherwise false "" "Pass Def Issubset (self, *args, **kwargs): # Real signature Unknown" "" "Report whether a Nother set contains this set. Whether it is a subsequence "" "Pass Def Issuperset (self, *args, **kwargs): # Real signature Unknown" "" Report whether this set contain s another set.    is the parent sequence "" "Pass def pop (self, *args, **kwargs): # Real Signature Unknown"" "Remove and return an arbitrary set element. Raises keyerror if the set is empty. remove element "" "Pass def Remove (self, *args, **kwargs): # Real signature Unknown" "" Remove an element from a set;         It must be a member. If the element is not a member, raise a keyerror. Removes the specified element without the error "" "Pass Def symmetric_difference (self, *args, **kwargs): # Real signature Unknown" "" Return t He symmetric difference of both sets as a new set.    symmetric intersection (i.e. all elements is in exactly one of the sets.) "" "Pass Def symmetric_difference_update (self, *args, **kwargs): # Real signature Unknown '" "Update a set with th e symmetric difference of itself and another.  symmetric intersection, and updated to a in "" "Pass Def Union (self, *args, **kwargs): # Real signature Unknown" "" Return the Union of sets as A new set.    The i.e all elements is in either set.) "" "Pass def update (self, *args, **kwargs): # Real signature Unknown '" "" Update a set with theUnion of itself and others. Update "" "Pass

B, Data type module example

Se = {11,22,33,44,55}be = {44,55,66,77,88}# Se.add ($) # print (SE) #添加元素, cannot print directly! # # # # se.clear () # Print (SE) #清除se集合里面所有的值, cannot clear a single # # ce=be.difference (SE) #se中存在, a value that does not exist in be, must be assigned to a new variable # print (CE) # # # SE . Difference_update (BE) # print (SE) #在se中删除和be相同的值, cannot be assigned to a new variable, enter the conversion first, then print, or print directly! # Se.discard (one) # print (SE) #移除指定元素, remove does not exist, will not error # Se.remove (one) # print (SE) #移除指定的元素, remove the non-existent will error # Se.pop () # p    Rint (SE) #移除随机的元素 # # # Ret=se.pop () # Print (ret) #移除元素 and can assign the removed element to another variable # CE = se.intersection (BE) # print (CE)     #取出两个集合的交集 (same Element) # se.intersection_update (BE) # print (SE) #取出两个集合的交集 and updated to se collection # ret = Se.isdisjoint (BE) # print (ret) #判断两个集合之间又没有交集, if there is a intersection return false, there is no return true# Ret=se.issubset (BE) # print (ret) #判断se是否是be集合的子序列, if it is returned true, is not returned flase# ret = SE . Issuperset (BE) # print (ret) #判断se是不是be集合的父序列, if it is true, returns flase# Ret=se.symmetric_difference (BE) # print (ret) #对称交 Set, remove all but the different elements # se.symmetric_difference_update (BE) # print (SE) #对称交集, take out the different elements and update to the SE collection # ret = se.unIon (BE) # print (ret) #并集, sets two elements into a new variable 

2, the depth of the copy

A, number, and string

For numbers and strings, assignments, shallow copies, and deep copies are meaningless because they always point to the same memory address.

Import copy# ######### number, string ######## #n1 = 123# N1 = "I am Alex age" Print (ID (n1)) # # # # # # # #n2 = N1print (id (n2)) # # # # Shallow copy Shell # #n2 = copy.copy (n1) print (ID (n2))  # # # deep Copy # #n3 = copy.deepcopy (n1) print (ID (n3))

B. Other basic data types

For dictionaries, Ganso, and lists, the changes in the memory address of the assignment, the shallow copy, and the deep copy are different.

1. Assign Value

Assignment, just create a variable that points to the original memory address, such as:

N1 = {"K1": "Zhangyanlin", "K2": 123, "K3": ["Aylin", 456]}n2 = N1

2. Shallow copy

Shallow copy, creating only the first layer of data in memory

Import copyn1 = {"K1": "Zhangyanlin", "K2": 123, "K3": ["Aylin", 456]}n3 = copy.copy (n1)

3. Deep copy

Deep copy, recreate all the data in memory (excluding the last layer, i.e., Python's internal optimization of strings and numbers)

3. Functions

Function: A function code is encapsulated in a function, it will not need to be repeated later, only the function can be called
Object-oriented: classify and encapsulate functions to make development "faster, better and stronger ..."

The definition of a function has the following main points:

def: A keyword that represents a function
Function name: the names of functions, which are called later by function name
Function Body: A series of logical calculations in a function, such as sending a message, calculating the maximum number in [11,22,38,888,2], etc...
Parameters: Providing data for the function body
Return value: Once the function has finished executing, it can return data to the caller.

1. Return value

A function is a function block that executes successfully or is required to inform the caller by the return value.

In the above points, it is more important to have parameters and return values:

def send SMS ():      code to send SMS ...    If send succeeded:    return True  else: return    False while    true:      # each time the send SMS function is executed, the return value is automatically assigned to result  #, Can write log according to result, or resend operation    result = Send SMS ()  if result = = False:    SMS Send failed ...

There are three different parameters to the function:

General parameters

# ######### define function #########

# name is called the formal parameter of function func, abbreviation: Parameter
def func (name):
Print Name

# ######### Execute function #########
# ' Zhangyanlin ' is called the actual argument of function func, abbreviation: argument
Func (' Zhangyanlin ')

Default parameters

def func (name, age = 18):

Print "%s:%s"% (name,age)

# Specify parameters
Func (' Zhangyanlin ', 19)
# using default parameters
Func (' Nick ')

Note: Default parameters need to be placed at the end of the parameter list
  

Dynamic parameters

def func (*args):   print args# execution mode one func (11,33,4,4454,5) # execution mode two li = [11,2,2,3,3,4,54]func (*li)

def func (**kwargs):   print args  # execution mode one func (name= ' Wupeiqi ', age=18) # execution mode Two li = {' name ': ' Wupeiqi ', age:18, ' Gender ': ' Male '}func (**li)

def func (*args, **kwargs):   print args  print Kwargs

Message instance:

def email (p,j,k):  import smtplib from  email.mime.text import mimetext from  email.utils import formataddr   set = True  try:    msg = Mimetext (' j ', ' Plain ', ' utf-8 ') #j message content    msg[' from ' = Formataddr (["Wu Jianzi", ' Wptawy@126.com '])    msg[' to '] = formataddr (["Leave", ' 424662508@qq.com '])    msg[' Subject '] = "K" #k主题     server = Smtplib. SMTP ("smtp.126.com")    server.login ("wptawy@126.com", "ww.3945.59")    server.sendmail (' wptawy@126.com ') , [P], msg.as_string ())    server.quit ()  except:    set = False  return trueformmail = input ("Please enter the recipient's mailbox: ") Zhuti  = input (" Please enter message subject: ") Neirong = input (" Please enter message content: ") Aa=email (Formmail,neirong,zhuti) if AA:  print (" Mail sent successfully! ") else:  print ("message sent failed!")



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.