Python Road "Second article": Python Basics (i)

Source: Internet
Author: User

Function of the understanding of the process: according to the business logic from the top to bottom code function: The function of the code to encapsulate a function, the future will not need to repeat the writing, only call the function function is your program has good extensibility, reusability. The same function is recommended if you use more than 3 times. Raizhong: Not rote function can be understood as a function block, you have a large function split into a piece, with a function of the time to call a function block can! The function can be understood as: Lego bricks, give you a piece of it, you can use these blocks to make up anything you want, function! Functions can call functions! The function of the main function is to concatenate functions and invoke them! The function itself cannot be executed on its own if you don't call it and never do it!
#python name is test.py#-------------------------------def func1 ():    passdef Func2 ():    passdef func3 ():    Passdef Func4 ():    func1 ()    func2 ()    func3 () if __name__ = = ' __main__ '    #调用上面的函数, judged, looped calls, etc.    #函数里也可以调用函数例子: Def func4 (): #__name__  This is used to judge if you are to put this program when the module import, his __name__ is equal to the file name of the program, if the script is executed manually such as: Python test.py  so __name__ is equal to __main__ so, we can use him to make judgments, if you are manually executed I will run my tune function execute if the following statement, if you are calling the module I below if the statement after the sentence will not be executed! Only if the module is used!
#如果函数当模块导入的时候, he imports the name of the function, the content is not imported, and when you go to invoke it, he goes to import the information in the function.

Custom functions

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

The code above is process-oriented programming, but if the alarm is more then hundreds of code needs to add how to do it? Copy and paste that would be dead! Look at the following code:

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%:

The second is certainly better than the first reusability and readability, which is the difference between functional programming and process-oriented programming:

    • Process oriented: More needs a line of code! Logical chaos, and cut code duplication, not easy to modify the reusability of poor!
    • 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 ..."

Second, function-type programming

functional programming is most important to enhance the reusability and readability of code :

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.

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    # After that, the log can be written according to result, or the operation     result = Send SMS ()    if result = = False:        log, SMS send 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 Alert mail ()    #发送邮件提醒    connect the mailbox server    send mail    off connect def hard drive Alert Mail ()    #发送邮件提醒    Connect mailbox server    Send mail    close connection 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 Alert Mail ()

Use the function: (the code is significantly less, the repetition of the internal use to the parameter call!) )

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:

    1. General parameters
    2. Default parameters
    3. Dynamic parameters

General parameters:

# ######### definition Function ######### # name is called function func formal parameter, abbreviation: Parameter def func (name):    print name# ######### execute function ######### #  ' Luoti Anshuai ' is called the actual parameter of function func, abbreviation: argument func (' Luotianshuai ')

But there's a problem with common parameters! When you define parameters, you define a number of parameters, you must give him a few parameters when you call or error!

def func (Name,shuai):    print Name,shuai#func (' Luotianshuai ') func (' Luotianshuai ') #报错内容: Typeerror:func () takes Exactly 2 arguments (1 given)

Default parameters:

He will use the default parameters when you do not give him parameters!

def func (name, age =):        print "%s:%s"% (name,age) # Specify parameter func (' Luotianshuai ', 19) # Use default parameter func (' Luotianshuai ')
Note: Default parameters need to be placed at the end of the parameter list, or you will get an error! The reason: His parameter assignment is an assignment of one value. If you provide formal parameters for the default values, you will have to sort backwards by default in order for you to give those arguments that are not accompanied by default values!

Dynamic Parameters:

Dynamic parameters can be dynamically expanded to the number of function parameters!

Example: 1 (multiple single variables, consolidated Narimoto Group)

def func (*args):    print args# execution mode one func (11,33,4,4454,5) #输出结果: 11,33,4,4454,5# execution Mode two li = [11,2,2,3,3,4,54]func (LI) # Output: ([11,2,2,3,3,4,54]) #如果想输入的列表, do not want the list to address only one element of the tuple, but let the elements of the list become the elements of the tuple plus * can be func (*li) #输出结果: (11,2,2,3,3,4,54) ######### ################################################### #1, accepts multiple parameters 2, internally automatically constructs tuples 3, sequences, *, avoids inner tectonic tuples

Example: 2 (integration as dictionary variable)

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

Example: 3 (Integration of *args,**args)

def func (*args, **drgs):    print args    print dargs# example: Func (11,22,33,44,k1= ' Luotianshuai ', k2= ' Shuaige ') (11, 22, () {' K2 ': ' Shuaige ', ' K1 ': ' Luotianshuai '}

Extensions: Sending an email instance

Import smtplibfrom email.mime.text import mimetextfrom email.utils import formataddrdef email message:    msg = Mimetext ("Mail Alarm test", ' plain ', ' utf-8 ')    msg[' from ' = Formataddr (["Shuaige", ' [email protected] ') #发件人和发件邮箱    msg [' to '] = FORMATADDR (["Handsome", ' [email protected] ')    msg[' Subject '] = message  #这里我调用了参数    server = Smtplib. SMTP ("smtp.test.com")    server.login ("[Email protected]", "Pwdnq.buzhidao")    server.sendmail (' [Email Protected] ', [' [email protected] ',], msg.as_string ())    server.quit () if __name__ = = U ' __main__ ':    CPU =    Disk =    RAM =    $ for i in range (1):        If CPU >:            alert = U ' CPU problem '   #这里设置了一个变量            Email (a Lert)  #这里调用函数的时候引用了上面的变量, when the function is executed the formal parameter will be replaced, message= ' CPU problem '  send mail!        if disk >:            alert = u ' HDD problem '            email (alert)        if ram>:            alert = u ' memory problem '            email ( Alert
Built-in functions

Built-in functions: (Python uses some of the methods commonly used in each module for ease of use)

After remembering, you need to know how to check:

>>> li = [11,22,33,44]>>> type (LI)  #查看数据类型 <type ' list ' >  >>> dir (list)  # View those methods that the type contains >>>HELP (list)  #查看类型中包含的方法的详细说明
Scope of the function

Look at the following example:

Def say ():    name = "Tianshuai"    print Namesay () This output: Tianshuai  # is no problem, so look at the following example: Def say ():    name = " Tianshuai "    print Namesay () Print name # This can be called, no, will error! The scope of the function is that the variable defined in the function cannot be used outside!

Look at the following example:

name2 = "Shuaige" Def Say ():    name = "Tianshuai"    print name    print Name2say () output result: Tianshuaishuaige
Summary: The scope of the function is that the variable defined in the function cannot be used outside! But externally globally defined global variables can be used within a function. For example: You can see things in the house and crooked things in the house, but outside of the house you only see things outside the house! Cause prevents variable collisions when function calls!

Question: Can I change the global variable I define outside the function? #看下面的例子:

name2 = "Shuaige" Def Say ():    name = "Tianshuai"    name2 = "Shuaige is Shuaige"    print Name,name2say () print name2# Output: Tianshuai shuaige is shuaige   #在函数内改变了shuaige  #但是外面调用还是没有改变!

But I just want to change the global variables in the function can it? OK!

#但是我就想在函数内改掉这个变量怎么办呢? Call the global parameter inside the function! (This feature is available, but not recommended!) You can easily cause confusion when you change local variables to global variables name2 = "Shuaige" Def Say ():    global name2    name = "Tianshuai"    name2 = "Shuaige is Shuaige"    print Name,name2say () print name2 output result: Tianshuai Shuaige is Shuaigeshuaige
Return parameter
def count (): For    I in range (1,10):        If i = 5:            return        else:            print i    , print "Hello world"   #所以当i = When I was 5, I just jumped out of the function, and this is not going to be printed! Not a loop!!! COUNT () output results: 1234

Return is generally written at the end of the function, and you want to see the result of the function's execution! Then judge the program behind it. Look at the following example

def count ():    name = "Tianshuai" for    I in range (1,10):        If i = = 5:            print "Hello"        else:            print I    return name    #在这里加了一个return user = count () if user = = "Tianshuai":   #然后判断, look at the results of the execution!    print "Oh Shuaige is coming"  execution Result: 1234hello6789oh Shuaige is coming   #这里看下! The judgment above has been executed! So return this to the name of the value of the output!

File operations

When working with files, you typically need to go through the following steps:

    • Open File
    • Manipulating files

First, open the file

The file handle = files (' File path ', ' mode ') #python中打开文件有两种方式, i.e. open (...) and file (...  ), which are essentially called internally by the latter, and are recommended to use open. 3.0 after the file method is used for other, the open method will automatically help you find the method where he called!

When you open a file, you need to specify the file path and how you want to open the file, and then open it to get the file handle and manipulate it later through the file handle.

The mode of opening the file is:

    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

    • r+, can read and write files. "readable; writable; can be added"
    • w+, meaningless
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

    • Rb
    • Wb
    • Ab

Second, operation Operation

class file (object): Def close (self): # real signature unknown;  Restored from __doc__ close file "" "Close () None or (perhaps) an integer.                 Close the file.  Sets data attribute. Closed to True.  A closed file cannot is used for further I/O operations.  Close () May is called more than once without error.        Some Kinds of File objects (for example, opened by Popen ()) could return an exit status upon closing. "" "Def Fileno (self): # real signature unknown;                 Restored from __doc__ file descriptor "" "Fileno (), integer" File descriptor ".        This is needed for Lower-level file interfaces, such Os.read (). "" "Return 0 def Flush (self): # real signature unknown;  Restored from __doc__ flush file internal buffer "" "Flush () None. Flush the internal I/O buffer. "" "Pass Def Isatty (self): # real signature unknown;        Restored from __doc__ to determine if the file is a consent TTY device"" "Isatty () True or false. True if the file is connected to a TTY device. "" "Return False def Next (self): # real signature unknown; Restored from __doc__ gets the next row of data, does not exist, the error "" "" "" "" "" "" X.next (), the next value, or raise Stopiteration "" "p The Size=none (self, the): # Real signature unknown;                 Restored from __doc__ reads the specified byte data "" "Read ([size]), read at the most size bytes, returned as a string.        If the size argument is negative or omitted, read until EOF is reached.  Notice that while in non-blocking mode, less data than what is requested may be returned, even if no size parameter        was given. "" "Pass Def Readinto (self): # real signature unknown;  Restored from __doc__ read to buffer, do not use, will be abandoned "" "Readinto (), undocumented. Don ' t use this; It may go away. "" "Pass Def ReadLine (self, size=none): # Real signature unknown;       Restored from __doc__ reading only one row of data "" "ReadLine ([size]), next line from the file, as a string.  Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line is returned then)        .        Return an empty string at EOF. "" "Pass Def readlines (self, size=none): # Real signature unknown;  Restored from __doc__ reads all data and saves a list of values, "" "ReadLines ([size]), based on line break, and list of strings, each a lines from                 The file.        Call ReadLine () repeatedly and return a list of the lines so read.        The optional size argument, if given, is a approximate bound on the all number of bytes in the lines returned. "" "return [] def seek (self, offset, whence=none): # Real signature unknown;  Restored from __doc__ specifies the position of the pointer in the file "" "Seek (offset[, whence]), None.                 Move to new file position.  Argument offset is a byte count.  Optional argument whence defaults to      0 (offset from start of file, offset should is >= 0);  Other values is 1 (move relative to position, positive or negative), and 2 (move relative to end of  file, usually negative, although many platforms allow seeking beyond the end of a file).  If the file is opened in text mode, only offsets returned by tell () is legal.        Use of other offsets causes undefined behavior.        Note that not all file objects is seekable. "" "Pass Def Tell (self): # real signature unknown; Restored from __doc__ gets the current pointer position "", "Tell ()", "present file position, an integer (could be a long integer). "" "Pass def truncate (self, size=none): # Real signature unknown;  Restored from __doc__ truncates the data, leaving only the specified previous data "" "Truncate ([size]), None.                 Truncate the file to in the most size bytes.        Size defaults to the current file position, as returned by Tell (). "" "Pass Def Write (selF, P_str): # Real signature unknown;  Restored from __doc__ write content "" "Write (str)-None.                 Write string str to file.        Note that due to buffering, flush () or close () is needed before the file on disk reflects the data written. "" "Pass Def writelines (self, sequence_of_strings): # Real signature unknown;  Restored from __doc__ writes a list of strings to the file "" "Writelines (sequence_of_strings), None.                 Write the strings to the file.  Note that newlines is not added. The sequence can is any iterable object producing strings.        This is equivalent to calling write () for each string. "" "Pass Def Xreadlines (self): # real signature unknown;                 The restored from __doc__ can be used to read the file line by row, not all "" "Xreadlines ()-returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the Xreadlines module.        "" "Pass 

Third, with method

To avoid forgetting to close a file after opening it, you can manage the context by: (We recommend that you open the file using this method)

With open (' Log ', ' R ') as F:         ...

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:

With open (' Log1 ') as Obj1, open (' log2 ') as Obj2:    Pass

Example: For example, to modify the nginx.conf file and then rollback how to do it?

With open (' nginx.conf ', ' R ') as Obj1,open (' Nginx.conf.new ', ' W ') as Obj2: for    i in Obj1.readlines ():        i = I.strip ()        Print I        obj2.write (i)        obj2.write (' \ n ') #读取nginx. conf each line is then stored in the new file Nginx.conf.new!

Python Road "Second article": Python Basics (i)

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.