Python function explained

Source: Internet
Author: User

Python functions

I. Background

Before learning the function, always follow: process-oriented programming, that is, according to the business logic from the top to the bottom of the implementation of functions, often with a long code to achieve the specified function, the most common development process is to paste the copy, that is, the previous implementation of the code block copied to the current function, as follows:

    While True:          if CPU utilization > 90%:              #发送邮件提醒              Connect mailbox server              Send mail              off connection                    if hard disk use space > 90%:              #发送邮件提醒              Connect mailbox server              Send mail              close connection                    If memory consumption > 80%:              #发送邮件提醒              Connect mailbox server              Send mail              close connection  

Fixed eye A look at the above code, the IF condition statement under the content can be extracted out of the public, as follows:

def send mail (content)      #发送邮件提醒      connect a mailbox server to      send mail      off connection while        True:            If CPU utilization > 90%:          send mail (' CPU alert ')            if hard disk use space > 90%:          send mail (' HDD alert ')            

For the two implementations above, the second must be better than the first reusability and readability, in fact, this is the difference between functional programming and process-oriented programming:

    • 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 ..."

Functional programming The most important thing is to enhance the reusability and readability of code

ii. definition and use

    def function name (parameter):                       ...          function Body          ...          return value  

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:

    defSend SMS (): Code to send SMS ...ifSend success:returnTrueElse:              returnFalse whileTrue:#each time a send SMS function is executed, the return value is automatically assigned to result        #after that, the log can be written according to result, or the operation will be re-sent .result=Send SMS ()ifresult = =False: Log, SMS send failed ...

There are three different parameters to the function:

    • General parameters
    • Default parameters
    • Dynamic parameters

1. General parameters

    # ######### defining functions #########             # name is called the formal parameter of function func, abbreviation:  parameter    def func (name):           Print name             # ######### execution function #########       #   ' Wupeiqi ' is called the actual parameter of function func, abbreviation:   argument    func ('wupeiqi')  

2. Default function

    def func (name, age =):                    print"%s:%s" %(name,age)             # Specifying parameters      Func ('wupeiqi', +)      #  using default parameters      Func ('Alex')            Note: Default parameters need to be placed at the  end of the parameter list

3. Dynamic function

    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)  
    defFunc (* *Kwargs):Printargs#execution Mode oneFunc (name='Wupeiqi', age=18)            #mode of execution twoLi = {'name':'Wupeiqi', Age:18,'Gender':'male'} func (**li)
    def func (*args, * *Kwargs)                :print  args          print Kwargs  

Extension: Sending an instance of a message

    ImportSmtplib fromEmail.mime.textImportMimetext fromEmail.utilsImportformataddr msg= Mimetext ('Message Content','Plain','Utf-8') msg[' from'] = FORMATADDR (["Wu Jianzi",'wptawy@126.com']) msg[' to'] = FORMATADDR (["Leave",'424662508@qq.com']) msg['Subject'] ="Theme"Server= Smtplib. SMTP ("smtp.126.com", 25) Server.login ("wptawy@126.com","Email Password") Server.sendmail ('wptawy@126.com', ['424662508@qq.com',], msg.as_string ()) Server.quit ()
View Code

Python function explained

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.