Python Basics: Custom Functions

Source: Internet
Author: User

I. BACKGROUND

Before learning the function, always follow: process-oriented programming, that is, according to 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 previously implemented 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

Butt eye Look at the above code, if the contents of the statement 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 Alarm ')      if hard disk use space > 90%:        send mail (' HDD alert ')      if memory consumption > 80%:

  

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 of functions

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

  

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.

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

1. Return value

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

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:        record log, SMS send failed ...

  

1. Return value

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

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:        record log, SMS send failed ...

  

2. Parameters

Why do we have parameters?

DEF CPU Alert mail ()    #发送邮件提醒    Connect mailbox server    Send mail    off connect def hard drive Alert Mail ()    #发送邮件提醒    Connect mailbox server    Send mail    Turn off Connect def Memory alert Mail ()    #发送邮件提醒    Connect mailbox server    Send mail    close connection while True:     if CPU utilization > 90%:        CPU Alert mail ()     if hard disk use space > 90%:        hdd alert mail ()     if memory consumption > 80%:        Memory Alarm message () above example, no parameter implementation

  

def send mail (message content)    #发送邮件提醒    connect a mailbox server to    send mail    off connection while True:     if CPU utilization > 90%:        Send mail ("CPU alarm up.")     if hard disk uses space > 90%:        send mail ("hdd alarm up.") ")     if memory consumption > 80%:        Send mail (" Memory alarm up. ")

  

There are three different parameters to the function:

    • General parameters
    • Default parameters
    • Dynamic parameters
# ######### definition Function ######### # name is called function func formal parameter, abbreviation: Parameter def func (name):    print name# ######### execute function ######### #  ' Wupei Qi ' is called the actual parameter of function func, abbreviation: argument func (' Wupeiqi ') common parameter

  

def func (name, age =):        print "%s:%s"% (name,age) # Specify parameter func (' Wupeiqi ', 19) # Use default parameter func (' Alex ') Note: Default parameters need to be placed in the parameter list at the end of the default 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) dynamic parameter one

  

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)
Dynamic parameter Two
def func (*args, **kwargs):    print args    print Kwargs

  

Python's variable parameter

*args and **dargs are two mutable parameters of Python, and the difference is that *args is a Tuple,**dargs is a dict.

When *args and **dargs are used, the *args must be placed in front of the **dargs.

For example:

def func (A, B, *c):

Pass

function Func has at least two parameter variable parameters placed in tuple C

def func (*c): or def func (**DC) parameter indeterminate

def func (A, *c, **DC): You can share *args and **dargs, but be sure to put the *args in front

Python Basics: Custom Functions

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.