Python Basics 3 functions, recursion, built-in functions

Source: Internet
Author: User
Tags define local variable scope

The content of this section

1. Basic function syntax and features

2. Parameters and Local variables

3. return value

Nested functions

4. recursion

5. Anonymous Functions

6. Introduction to Functional programming

7. Higher-order Functions

8. Built-in Functions

Restudying 1. Collection

Main Functions:

    1. Go heavy

    2. Relationship test, intersection \ difference set \ set \ Inverse (symmetric) difference set

>>> a = {1,2,3,4}>>> b ={3,4,5,6}>>> a{1, 2, 3, 4}>>> type (a) <class ' Set ' >>& gt;> a.symmetric_difference (b) {1, 2, 5, 6}>>> b.symmetric_difference (a) {1, 2, 5, 6}>>> >> > >>> a.difference (b) {1, 2}>>> a.union (b) {1, 2, 3, 4, 5, 6}>>> a.issua.issubset (a.issuper Set (>>> a.issubset (b) False
2. tuples

Read-only list, only count, index 2 methods

Role: If some data do not want to be modified, can save Narimoto group, such as identity card list

3. Dictionary key-value to
    1. Characteristics:

    2. No order

    3. Go heavy

    4. Fast query speed, much faster than the list

    5. Consumes more memory than list

Why would queries be faster? Because he is a hash type, what is a hash?

The hashing algorithm maps a binary value of any length to a shorter fixed-length binary value, a small binary value called a hash Value. A hash value is a unique and extremely compact numeric representation of a piece of Data. If you hash a clear text and even change only one letter of the paragraph, subsequent hashes will produce different values. To find two different inputs that hash the same value, it is not possible to compute, so the hash value of the data can verify the integrity of the Data. Typically used for quick find and encryption algorithms

Dict will turn all the keys into a hash table and then sort the table so that when you look up a key in the data dictionary by data[key, Python will first hash the key into a number and then take the number to the hash table without that number. If so, get the index of this key in the hash table and get the index to the memory address of the value corresponding to this key.

4. Character encoding

first, python2.

    1. The default encoding in PY2 is ASCII

    2. The code declaration at the beginning of the file is to tell the program that explains it to read the code into memory, because in memory, this code is actually stored in the bytes binary format, but even the 2 binary stream can be converted to 2 streams in different encoding formats, you know?

    3. If the file header is declared #_*_coding:utf-8*_, you can write chinese, do not declare, python in the processing of this code by ascii, obviously error, add this declaration, the inside of the code is all Utf-8 format

    4. In the case of #_*_coding:utf-8*_, you declare the variable if it is written name=u "big health", that character is Unicode format, do not add this u, then you declare the string is utf-8 format

    5. Utf-8 to GBK how to turn, UTF8 first decode into unicode, then encode into GBK

besides, python3.

    1. Py3 in the default file encoding is utf-8, so you can directly write chinese, do not need to file header declaration code, dry Beautiful

    2. The variable you declare is Unicode encoding, not utf-8, because the default is Unicode (unlike in py2, you want to declare it directly to Unicode and add a U before the variable), and if you want to turn into gbk, direct Your_str.encode ("gbk" ) that can

    3. But py3, you in Your_str.encode ("gbk"), feel as if also added an action, that is, encode data into bytes, I rub, this is how a situation, because in py3, str and bytes made a clear distinction, You can understand that as bytes is the 2 stream, you will say, I see not 010101 such a 2, that is because Python to allow you to manipulate the data and at the memory level to help you to do a layer of encapsulation, or let you directly see a bunch of 2 binary, can you see which character corresponds to which paragraph 2 binary? What the? Your own conversion, come on, you even more than 2 digits of the number plus and minus operations are laborious, or save worry bar.

    4. Then you said, there seems to be a bytes in the py2, yes, but py2 bytes only to str made an individual name (python2 str is bytes, py3 str is unicode), there is no like py3 to show you a more layer of encapsulation, But in fact, its interior is Encapsulated. So let's say, whether It's 2 or three, from hard disk to memory, the data format is 101,012 to-->b ' \xe4\xbd\xa0\xe5\xa5\xbd ' bytes type--follow The specified code to the text you can read

Coding applications more than the scene should be a reptile, the internet, many websites with a very miscellaneous encoding format, Although the overall trend has become utf-8, but now still very miscellaneous, so crawling Web pages need you to do a variety of code conversion, but life is becoming better, looking forward to a world without transcoding.

finally, encode is a piece of fucking shit, noboby likes it.


1. Function basic syntax and feature background summary

Now the boss let you write a monitoring program, monitor the system status of the server, when the use of indicators such as cpu\memory\disk more than the threshold of the e-mail alarm, you emptied all the knowledge, wrote the following code

While True:if CPU utilization > 90%: #发送邮件提醒 connect mailbox server send mail off connection if hard disk uses space > 90%:        #发送邮件提醒 connect a mailbox server send mail close connection if memory consumption > 80%: send mail #发送邮件提醒 connection Mailbox server Close connection

The above code realizes the function, but even the neighbor old Wang also saw the clue, Lao Wang kindly touched the face of your son, said, you this duplicate code too much, every time the alarm to rewrite a piece of code, too low, so there are 2 problems:

    1. Too much code duplication, kept copy and paste not in line with high-end programmer temperament

    2. If you need to modify this code in the future, such as to join the mass function, then you need to use all the code in the place to modify it again

You think Lao Wang is right, you do not want to write duplicate code, but do not know how to do, Lao Wang seems to see your mind, at this time he picked up your son, smiled and said, in fact, it is very simple, just want to repeat the code extracted, put in a public place, a name, who want to use this code, the name of the call on the line As follows

def send mail (content) #发送邮件提醒 connect mailbox server send mail close connection while True:if CPU utilization > 90%: send mail (' CPU alert ') If HDD uses space > 90%: send mail (' HDD alert ') if memory consumption > 80%: send mail (' memory alarm ')

You look at the code written by Lao wang, imposing a magnificent, majestic atmosphere, the code reveals a restrained arrogance, thought, Lao Wang This person is really not general, suddenly to his background more interested in, Ask Lao wang, These fancy play how do you know? Lao Wang kissed your son, smoothed out the beard that does not exist, lightly said, "the old man, when young, the division from the Kinsisa of the silver horn king", you listen to the "silver corner king" of the words, not by the Jiao body a shock, thought, true nb, no wonder the code written so 6, this "silver horn king" That year in the lake but named sizable the name of the big, but unfortunately later over-indulgence, died in 2016, it is a pity, only left his brother alone when the two brothers fought down the Jiangshan. At this time you look at the old king left the figure, feel your son and he more and more like ...


What is a function?

function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, the specific difference, we will say later, the function of programming in English also has a lot of different names. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called Method.

Definition: a function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

Characteristics:

    1. Reduce duplicate code

    2. To make the program extensible

    3. Make programs easier to maintain

Syntax definitions
def sayhi (): #函数名 print ("Hello, I ' m Nobody!") sayhi () #调用函数

can take parameters

#下面这段代码a, b = 5,8c = A**bprint (c) #改成用函数写def Calc (x, y): res = x**y return res #返回函数执行结果 c = Calc (b) # result assigned to c variable print (c)
2. function parameters and local variables

A parameter variable allocates a memory unit only when it is called, releasing the allocated memory unit immediately at the end of the Call. therefore, the formal parameter is only valid inside the Function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the Parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

650) this.width=650; "src=" http://images2015.cnblogs.com/blog/720333/201608/720333-20160805142111497-1945389864.png "/>


Default parameters

Look at the code below

def stu_register (name,age,country,course): print ("----enrolled student Information------") print ("name:", name) print ("age:", age) print ("nationality:", Country) print ("course:", course) stu_register ("king shanbao", "a", "cn", "python_devops") stu_register ("zhang jiaochun", +, "cn", "linux ") Stu_register (" Liu Lao root "," CN "," linux ")

Found country This parameter is basically "CN", just like we registered users on the site, such as the nationality of this information, you do not fill in, the default will be china, which is implemented by default parameters, the country into the default parameters is very simple

def stu_register (name,age,course,country = "CN"):

thus, This parameter is not specified at the time of invocation, and the default is cn, specified by the value you specify.

After turning the country into the default parameter, I moved the position to the last Side.

Key parameters

Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, But remember a requirement is that the key parameters must be placed after the position parameter.

Stu_register (age=22,name= ' Alex ', course= "python",)

Non-fixed parameters

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

def stu_register (name,age,*args): # *args will turn multiple incoming parameters into a tuple form print (name,age,args) stu_register ("Alex", 22) #输出 #alex () # The following () is the args, just because there is no value, so the empty stu_register ("jack", "a", "cn", "Python") #输出 # Jack (' cn ', ' Python ')

can also have a **kwargs

def stu_register (name,age,*args,**kwargs): # *kwargs will turn multiple incoming parameters into a dict form print (name,age,args,kwargs) stu_register (" Alex "," #输出 #alex () {} #后面这个 {} is kwargs, just because there is no value, so it is empty stu_register ("Jack", "+", "CN", "Python", sex= "Male", province= " Shandong ") #输出 # Jack (' CN ', ' Python ') {' province ': ' Shandong ', ' sex ': ' Male '}
Local variables
Name = "Alex Li" def change_name (name): print ("before change:", name) name = "king of gold horn, a man with tesla" print ("after Chang E ", name) change_name (name) print (" look outside name changed? ", Name)

Output

Before Change:alex liafter change gold angle king, a man with Tesla look outside to see the name changed? Alex Li

Global vs. Local Variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.

The global variable scope is the entire program, and the local variable scope is the subroutine that defines the Variable.

When a global variable has the same name as a local variable:

Local variables work in Sub-programs that define local variables, and global variables work Elsewhere.

3. return value

To get the result of the function execution, you can return the result using the return statement

Attention:

    1. The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function

    2. If return is not specified in the function, the return value of this function is None

Forcibly inserting knowledge points: nesting functions

Looking at the title above means that the function can also be nested functions? Of course

Name = "Alex" def change_name (): name = "Alex2" def change_name2 (): name = "Alex3" Print ("3rd layer print", name ) change_name2 () #调用内层函数 print ("2nd print", name) change_name () print ("outermost print", name)
4. recursion

Inside a function, you can call other Functions. If a function calls itself internally, the function is a recursive function.

Def Calc (n): print (n) if int (n/2) ==0:return n return calc (int (n/2)) Calc (10) output: 10521 recursive characteristics: 1. There must be a definite end condition of 2. Each time you enter a deeper level of recursion, the problem size should be reduced by 3 compared to the last Recursion. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) this data structure implementation, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of Frames. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to OVERFLOW.
5. Anonymous Functions lambda

An anonymous function is one that does not require an explicit function to be specified

#这段代码def Calc (n): return n**nprint (calc) #换成匿名函数calc = lambda n:n**nprint (calc (10))

You may say that it is not convenient to use this thing. oh, if it is so used, there is no yarn improvement, but the anonymous function is mainly used with other functions, as follows

res = map (lambda x:x**2,[1,5,7,4,8]) for i in Res:print (i)

Output

1
25
49
16
64

6. Higher-order Functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order Function.

def add (x,y,f): return F (x) + F (y) res = add (3,-6,abs) print (res)


This article from "amin blog" blog, declined reprint!

Python Basics 3 functions, recursion, built-in 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.