The "third piece" of Python basics

Source: Internet
Author: User

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:

differs from other high-level languages:
1. Declare the end of the function name with a colon.
2. It does not need to enclose the statement block with curly braces and indent it with the TAB key.

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

Instance:

def test_a ():         ' Hello World ' ' www.jeapedu.com' def test_b (varl,var2): #函数定义, formal parameter, provided to the user an interface.                  Print Val1,        'Entry programme'test_a () test_b ( ,'leave programme'

1. Return value

The

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 success:  return   else  :  return   while   #      each time the send SMS function is executed. #    result  = send SMS ()  if  result == False: logging, SMS sending failed ...  

2. Parameters

Why do we have parameters? Take a look at the following example:

If you do not define parameters, use the function: (each with the same function write a function, good code simplification?) )

def CPU Alarm message ()#Send an email reminderConnect mailbox server send mail close connectiondefHDD Alert mail ()#Send an email reminderConnect mailbox server send mail close connectiondefMemory Alert Mail ()#Send an email reminderConnect mailbox server send mail close connection whileTrue:ifCPU Utilization > 90%: CPU alert mail ()ifHDD Use space > 90%: HDD alert mail ()ifMemory Footprint > 80%: Memory alert Mail ()

The function has three different parameters:

  • General parameters
  • Default parameters
  • Dynamic parameters
  • 1, receive multiple parameters
    2, internal auto-construction tuple
    3, Sequence, *, avoid internal tectonic tuples

  • 1>>> Li = (1,2,3,4,5,66,'Alex')2>>>3>>>defFunc (*args):4...Printargs5 ... 6>>>func (LI)7((1, 2, 3, 4, 5, 66,'Alex'),)8>>> Func (*Li)9(1, 2, 3, 4, 5, 66,'Alex')Ten>>> Li = [1,2,3,4,5,66,'Alex'] One>>>defFunc (*args): A...Printargs -...PrintArgs[0] Get the element by subscript ->>>func (LI) the([1, 2, 3, 4, 5, 66,'Alex'],) ->>> Func (*Li) -(1, 2, 3, 4, 5, 66,'Alex') ->>>
General ParametersDefault ParametersDynamic Parameter OneDynamic Parameter TwoDynamic parameter Three

If the last formal parameter in a function definition has a * * (double star) prefix, all other keyword parameters other than the normal parameter will be placed in a dictionary passed to the function, such as:

1 defContacs (a,**b):2     Print "A is:%s"%a3      forIinchB:4         Printi +":"+str (b[i])5 6Contacs (saneri=1234567890,rain=007)#called7 8A is: 100#Execution Results9saneri:1234567890TenRain:7

Extension: Sending an instance of a message

ImportSmtplib fromEmail.mime.textImportMimetext fromEmail.utilsImportformataddrdefEmail (message): Msg= Mimetext ("Mail Alarm test",'Plain','Utf-8') msg[' from'] = FORMATADDR (["Saneri",'[email protected]'])#Sender and Sender mailboxmsg[' to'] = FORMATADDR (["Recipient",'[email protected]']) msg['Subject'] = message#Here I call the parameterServer= Smtplib. SMTP ("SMTP: COM", 25) Server.login ("[email protected]","Password") Server.sendmail ('[email protected]', ['[email protected]',], msg.as_string ()) Server.quit ()if __name__= = U'__main__': CPU= 100Disk= 500Ram= 50 forIinchRange (1):        ifCPU > 90: Alert= u'There 's a problem with the CPU'   #A variable is set here.Email (alert)#When the function is called, the above variables are referenced, and when the function is executed, the formal parameter is replaced, and the message= ' CPU problem ' sends the message!         ifDisk > 90: Alert= u'hard drive problem.'Email (alert)ifRam> 80: Alert= u'memory problem.'Email (alert)

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

If executing python test.py is equivalent to __name__ = = ' __mail__ '

Footsteps executed, __name_ ' value ==__mail__

The return statement is used to return (return) from a function, that is, to jump out of a function. Again, we can optionally return a value from the function.

1 defmaximum (x, y):2     ifX >y:3         returnx4     elifx = =y:5         return 'Two numbers equal'6     Else:7         returny8 9 Print(Maximum (2, 3))

Output:
3

Python applications are becoming more and more widely available, and to a certain extent, it relies on a large number of modules for programmers to use, and if you want to use modules, you need to import them.

Python has three ways to import modules:

Import ModName

From ModName import funcname as Rename

From ModName import FA, FB, FC or from modname import *

When the module is imported, it is based on the Sys.path path as a benchmark.

 1  import   sys  2   Print   Sys.path  4  7   result:  8  9  [ / Users/wupeiqi/pycharmprojects/calculator/p1/pp1   ",  '  

If the Sys.path path list does not have the path you want, you can add it by sys.path.append (' path ')

The "third piece" of Python basics

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.