Python path, Python Basics 3 Functions (third Week)

Source: Internet
Author: User

1, set unordered, non-repeating sequence, can be nested 2, function = = "  definition function, function body does not execute, only call function, function body only execute 1, def2, First name 3, function body 4, return value 5, parameter normal parameter specify parameter default parameter dynamic parameter *args** Kwargs Universal parameter *args,**kwargs6, supplement: a.def f1def f2 function re-assignment b.  reference c. Global variable read, all readable assignment, first global dictionary, list, modifiable = = "capitalization 3 , ternary operation 4, Lamba expression function: programming is divided into two types: process-oriented, object-oriented breakpoints: You can see the execution process of a function def f1 (): asdfasdfasdasdfas# 1, def  keyword, Creating a function #  2, function name # 3, () # 4, functional Body # 5, return value Send mail instance def sendmail ():     try:import  smtplibfrom email.mime.text import MIMETextfrom email.utils import  Formataddrmsg = mimetext (' Mail content ',  ' plain ',  ' utf-8 ') msg[' from '] = formataddr (["silver" ,  ' [email protected] ']) msg[' to '] = formataddr (["gold",  ' [email protected] ']) msg[' Subject '] =  ' theme ' Server = smtplib. SMTP ("smtp.126.com",  25) server.login ("[email protected]",  "123") server.sendmail (' [email  protected] ',  [' [email protected] ',  ], msg.as_string ()) server.quit ()     except:        #  Send failed          return  "failure"     else:         #  Send success         return  "cc" ret =  SendMail () print (ret) if ret ==  "cc":p rint (' Send success ') else:print ("send Failed") "" "# print (123) #  Def f1 (): #     print (123) #     #  in the function, once the return is executed, The function execution process terminates immediately #     return  "111" #     print (456) ## r  = f1 () # print (r) # def f2 (): #     print (123) ## r =  f2 () # print (r) If the function does not return a value, the Python auto default return none#  form parameter will return none# 1 by default if not return,python, Normal parameters (in strict order, The actual parameters are assigned to the formal parameters) # 2, default parameters (must be placed at the end of the parameter List) # 3, specifying parameters (assigning actual parameters to the prescribed formal parameters) # 4, dynamic parameters:#         *       default will pass in the parameters, all placed in the tuple,  f1 (*[1 ' 1,22,33,44]) #         **      default will pass in the parameters, all placed in the dictionary    f1 (**{"kl": "v1",   "k2": "v2"}) # 5, Universal parameters,    *args,**kwargs , A *  can only be in front, two *  only in the following default parameter Def  send (xxoo, content, xx= "ok"):p rint (xxoo, content, xx) # print ("send Mail success:",  Xxoo, content) return truesend (' Alex ',  "sb") send (' Alex ',  "sb",  "BB") general Parameters Def send ( xxoo,content):     print (xxoo,content)     return truesend (' Alex ', ' SB ") Specify parameter def send (xxoo,content):     print (xxoo,content)     return  truesend (' Alex ', ' sb ') def f1 (*args):     print (args,type (args)) li=[11,22,33, "alex ]F1 (li) F1 (*li) If there is * in front of the list, all values will be passed to the tuple and the dynamic parameters can be Received. Def f1 (**args):     print (args,type (args)) # f1 (n1= "alex", N2=18) dic = {' K1 ': "v1", "k2": "v2"}# f1 (kk=dic) F1 (**dic) Universal parameters, one *  only in front, two *  only in the back Def  f1 (*args,**kwargs):     print (args)     print (kwargs) F1 ( 11,22,33,44,k1= "v1", k2= "v2") uses dynamic parameters to implement the Format function s =  "i am {0}, age {1}". format ("alex "," print (s) s =  "i am {0}, age {1}". format (*["alex", +]) print (s) s1 =  "i am {name}, age {age}". format (name= "alex", age=18) print (s1) dic = {' name ': ' Alex ' , "age":18}s1 =  "i am {name}, age {age}". format (**dic) print (s1) supplemental 1:python  It has its own garbage collection mechanism, which automatically recycles Garbage. DEF&NBSP;F1 (a1,a2):     return a1 +a2def f1 (a1,a2):     RETURN&NBSP;A1*A2RET&NBSP;=&NBSP;F1 (8,8) print (ret) supplement 2: function parameter passing is a reference: def f1 (a1):     A1.append (999) li=[11,22,33,44]f1 (li) print (li) complements 3:#  Global variables, all scopes are readable #  "re-assigns" to global variables, requires global#  Special: list dictionary, modifiable, not re-assignedThe value #  all global variables must be all Uppercase. Name= "alex" def f1 ():     age =18    # global name  #  indicates that name is the global variable     # print (name)     # name.append ( 999)     print (age,name) def f2 ():    age = 19     print (age,name) F1 () F2 () example: functional Programming for login and registration #!/usr/bin/env python# -*- coding:utf-8  -*-# author:alex lidef login (username, password): "" "for user login: param username:   User entered user name:param password:  user entered Password: return: true, indicating successful login, false, login failed "" "f = open (" db " ,  ' r ') for line in f:line_list = line.strip (). split ("|") if line_list[0] == username and line_list[1] == password:return  Truereturn falsedef register (username, password): "" "for user registration:param username:  user name: param  password:  password: return:  Default None "" "f = open (" db ",  ' a ') temp = " \ n " + username + " | "  + passwordf.write (temp) f.close () def main (): t = input ("1: login; 2: Register") if t ==   "1": user = input ("please Enter user Name:") pwd = input ("please enter Password:") r = login (user, pwd) If r:print ("login Succeeded") else:print ("login Failed") elif t ==  "2": user = input ("enter user Name:") pwd  = input ("please Enter Password:") Register (user, pwd) main () #  ternary operation, trinocular operation, if else shorthand "" "if 1 ==  1:name =  "alex" else:name =  "SB" #  if  1==1  set up,# name =  " Alex "#  otherwise # name = " SB "name = " Alex " if 1 == 1 else   "SB" "" "lambda expression def f1 (a1):    return a1 + 100    &NBSP;F2&NBSP;=&NBSP;LAMBDA&NBSP;A1,&NBSP;A2=9:&NBSP;A1&NBSP;+&NBSP;A2&NBSP;+&NBSP;100RET&NBSP;=&NBSP;F1 (10) Print (ret) r2 = f2 (9) Print (r2) built-in function abs () all () any () bool () ascii () bin () Oct () hex () bytes () # abs absolute value # n = abs (-1) #  print (n) #  All true, only true # n = all ([1,2,3,none]) # print (n) #  as long as it is true # n  = any ([[],0, "", None]) # print (n) # 0,none, ", [],  ()    all for false#  note"   "there is a space in the middle, this is True. # print (bool ())) # ascii ()  #  automatic execution of objects  __repr__# class Foo:#      def __repr__ (self):#         return  " 444 "## n = ascii (Foo ()) # print (n) # bin ()   octal # oct ()   decimal # hex ()   Hex # print (bin (5)) # print (oct (9)) # print (hex ()) "" "# utf-8  a kanji: three bytes #  gbk  a kanji: two bytes # utf-8s =  "li jie" #  A byte 8 bits, a kanji three bytes #  0101010 10101010  101010101  0101010 10101010 101010101#     23     &nbsP;23      23           23      23      23  15#      2f     2a      2c            2c     2e      2f   f#  string Conversion byte type # bytes (as long as the converted string,  according to what Encoding) n = bytes ("li jie",  encoding= "utf-8 Print (n) n = bytes ("li jie",  encoding= "gbk") print (n) #  bytes into string new_str = str (bytes (" Li Jie ",  encoding=" utf-8 "),  encoding=" utf-8 ")" "" file operation open mode, the function for file processing file operation is divided into three steps: open file, manipulate file, close File #  1, Open File # file handle  = open (' file path ',  ' mode ') the mode of opening the file Is: # f = open (' db ',  ' r ')  #   "default" # f = open (' db ',  ' W ')  #  "unreadable; not present, create; empty content;" # f = open (' db ',  ' x ')  #  "unreadable, not present, created, present error" # f = open (' db ',  ' a ')  #  "readable;    not present" Create ; "+"   means that a file can be read and written: # f = open (' db ',  ' r+ ') Read and write "readable, writable" is used up to r+# f =  open (' db ',  ' w+ ') write read "readable, writable" w+ each time the file is written, the contents of the file are emptied first # f = open (' db ',  ' x+ ') write read "readable, writable" x+ Current file exists, error # f = open (' db ',  ' A + ') write read "readable, can write" a + each write a file, will write to the last "b" means to operate in bytes:rb   or   r+bwb  or  w+bxb  or  w+bab  or  a+b note: when opened in b, the content read is a byte type, and a byte type is required to write # f =  open (' db ', ' r ',  encoding= "utf-8") # data = f.read () # print (data, type (data)) # f.close () # f = open (' db ', ' r ') # data = f.read () # print (data,type (data )) # f = open (' db ', ' RB ') # data = f.read () # print (data,type (data)) # f  = open ("db",  ' A ') # f.write ("li Jie") # f.close () ## f = open ("db",  ' AB ') # f.write (bytes ("Li Jie ",  encoding=" utf-8 ")) # f.close () # f = open (" db ",  ' r+ ',  encoding=" utf-8 ") #  # f.fileno () # #  If open mode is not  b, read, reads by character # data = f.read (1) # #  tell The current pointer is in (bytes) # print (f.tell ()) # #  Adjustment is currently pointing to your position (bytes) # f.seek (f.tell ()) # #  Current pointer position starts to overwrite # f.write ("888") # f.close () # 2, action file # read ()  #  no parameters, read all; parameters,#                                      b, by byte #                                       No B , by character # tell ()   Get current pointer position (bytes) # seek (1)   pointer jumps to specified position (bytes) # write ()   Write data, b, byte; no b, character #  Close# fileno# flush  Strong Brush # readline  reads only one line of # truncate  truncation, the pointer is emptied after the # for loop file Object  f = open ( Xxx) # for line in f:#     print (line) # f = open (" DB ",  ' r+ ',  encoding=" utf-8 ") # f.seek (3) # f.truncate () # f.close () # f =  Open ("db",  ' r+ ',  encoding= "utf-8") # for line in f:#      print (line) #  through the source view function # 3, Close the file # f.close () # with open (' XB ')  as f:#      passwith open (' XB ')  as f:passwith can open multiple files at the same time, adding new features starting from 2.7. With open (' db ', ' r ', encoding= "utf-8")  as f1,open ("db1", ' W ', encoding= "utf-8")  as f2: Times = 0for line in f1:times += 1if times <= 10:f2.write (line) else:break Replacement file: with open (' db ', ' r ', encoding= "utf-8")  as f1,open ("db1", ' W ', encoding= "utf-8" ) &NBSP;AS&NBSP;F2:&NBSP;&NBSP;&NBsp; for line in f1:    new_str = line.replace ("alex", " Luchuan ")     f2.write (new_str) with open (' db1 ',  ' r ',  encoding= ' Utf-8 ')   As f1, open ("db2",  ' W ', encoding= "utf-8")  as f2:    for line  in f1:        if line ==  "xx":             f2.write ()              f2.write ()         # new_str  = line.replace ("alex",  ' St ')         # f2.write ( New_str)                 class  textiowrapper (_textiobase): "" "character and line based layer over a  bufferediobase object, buffer.encoding gives the name of the encoding that the  stream will bedecoded or encoded with. it defaults to  Locale.getpreferredencoding (False) .errors determines the strictness of encoding  and decoding  (seehelp (codecs. CODEC)  or the documentation for codecs.register)  anddefaults to  " Strict ". Newline controls how line endings are handled. it can be  None,  ', ' \ n ',  ' \ r ', and  ' \ r \ n '.   it works as follows:*  On input, if newline is None, universal newlines mode  isenabled. lines in the input can end in  ' \ n ',  ' \ r ',  or   ' \ r \, andthese are translated into  ' \ n '  before being returned  to thecaller. if it is  ',  universal newline mode is enabled,  but lineendings are returned to the caller untranslated. if  it has any ofthe other legal values, input lines are  only terminated by the givenstring, and the line ending is  Returned to the caller untranslated.* on output, if newline is  None, any  ' \ n '  characters written aretranslated to the system  default line separator, os.linesep. Ifnewline is  '  or  ' \ n ',  no translation takes place. if newline is anyof the other  legal values, any  ' \ n '  characters written are translatedto the  given string. if  line_buffering is true, a call to flush is implied when a  call towrite contains a newline character. "" " Def close (self, *args, **kwargs):  # real signature unknown Close File passdef  Fileno (self, *args, **kwargs):  # real signature unknown file descriptor Passdef flush ( self, *args, **kwargs):  # real signature unknown flush File Internal buffer Passdef isatty ( Self, *args, **kwargs):  # real signature unknown Determine if the file is a TTY device Passdef read ( Self, *args, **kwargs):  # real signature unknown reads the specified byte data passdef readable ( Self, *args, **kwargs):  # real signature unknown is readable passdef readline (self,  *args, **kwargs):  # real signature unknown reads only one row of data Passdef seek (self, * Args, **kwargs):  # real signature unknown the pointer position in the specified file passdef seekable (self, *args, **kwargs):  # real signature  unknown whether the pointer is operable Passdef tell (self, *args, **kwargs): # real signature  Unknown get pointer position passdef truncate (self, *args, **kwargs): # real signature  Unknown truncates data, Preserving only specified previous data passdef writable (self, *args, **kwargs):  # real signature Whether  unknown can write Passdef write (self, *args, **kwargs): # real signature  Unknown write content passdef __getstate__ (self, *args, **kwargs): # real signature  unknownpassdef __init__ (self, *args, **kwargs): # real signature  unknownpass@staticmethod # known case of __new__def __new__ (*args, **kwargs ):  # real signature unknown "" " Create and return a new  Object.  see help (type)  for accurate signature.  "" "passdef __next__ (self, *args, **kwargs):  #  real signature unknown "" " implement next (self) . " "" passdef __repr__ (self,  *args, **kwargs):  # real signature unknown "" " return repr (self).   "" "passbuffer = property (lambda self: object (), lambda self, v:  None, lambda self: none)   # defaultclosed = property (lambda self:  object (),  lambda self, v: none, lambda self: none)   #  Defaultencoding = property (lambda self: object (),  lambda self, v: none ,  lambda self: none)   # defaulterrors = property (lambda self:  object (),  lambda self, v: none, lambda self: none)   #  Defaultline_buffering = property (lambda self: object (),  lambda self, v: none, lambda  self: none)   # defaultname = property (lambda self: object (),  lambda self, v: none, lambda self: none)   # defaultnewlines  = property (lambda self: object (),  lambda self, v: none, lambda  self: none)   # default_chunk_size = property (lambda self: object (),  lambda self, v: none, lambda self: none)   # default_ Finalizing = property (lambda self: object (),  lambda self, v: none,  lambda self: none)   # default3.x

This article is from the "sweeping monk" blog, please be sure to keep this source http://luchuangao.blog.51cto.com/11311715/1861470

Python path, Python Basics 3 Functions (third Week)

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.