The third week of Python's Automated development learning---basic python learning

Source: Internet
Author: User
Tags define local square root variable scope

This week's content

1. Basic syntax and characteristics of functions

2. Parameters and Local variables

3. Return value

4. Recursive functions

5. Anonymous functions

6. Introduction to Functional programming

7. Higher-order functions

8. Built-in functions

---------Split Line------------

1. Basic syntax and characteristics of functions

What is a function? Definition: A function is a collection of a set of statements by a name (function name) to encapsulate, to execute this function, just 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
1 def sayhi (): #函数名 2     Print ("Hello, I ' m nobody! " )3  4 sayhi () #调用函数

2. Parameters and Local variables

Parametric the memory unit is allocated only when 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

Default parameters

1 def stu_register (name,age,country,course):2Print"----Registered Student information------")3Print"Name:", name)4Print"Age :", age)5Print"Nationality:", Country)6Print"Course:", course)7  8Stu_register ("Wang Shanbao", A,"CN","Python_devops")9Stu_register ("Zhang Jiaochun", +,"CN","Linux")TenStu_register ("Liu Lao Gen", -,"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

1 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.

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=, 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

1def stu_register (Name,age,*args): # *args turns multiple incoming parameters into a tuple form2 print (Name,age,args)3  4Stu_register ("Alex", A)5 #输出6#Alex A() #后面这个 () is args, just because no value is passed, so it is empty7  8Stu_register ("Jack", +,"CN","Python")9 #输出Ten# Jack +('CN','Python')

can also have a **kwargs

1def stu_register (Name,age,*args,**kwargs): # *Kwargs will turn multiple incoming parameters into a dict form.2 print (Name,age,args,kwargs)3  4Stu_register ("Alex", A)5 #输出6#Alex A() {} #后面这个 {} is Kwargs, just because no value is passed, so it is empty7  8Stu_register ("Jack", +,"CN","Python", sex="Male", province="Shandong")9 #输出Ten# Jack +('CN','Python') {'Province':'Shandong','Sex':'Male'}
Local variables
Name ="zhangsan"def changename (name):    print ("before name  ", name)    "Lisi"    print (" After name " , name) changename (name) print ("----", name)

Output

Before name Zhangsan
After name Lisi
----Zhangsan

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 within subroutines that define local variables, and global variables work in other places.

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

4. Recursive functions

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

1 def Calc (n):2 print (n)3     if int(n/2) ==0:4         returnN5     returnCalcint(n/2))6  7CalcTen)8  9 Output:Ten Ten One 5 A 2 - 1

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion

3. 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, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Recursive function Practical application case, two-point search

1data = [1,3,6,7,9, A, -, -, -, -, -, +, A, at, -, +, -, *]2  3  4 def binary_search (dataset,find_num):5 Print (DataSet)6  7     ifLen (DataSet) >1:8MID =int(Len (DataSet)/2)9         ifDataset[mid] = =find_num: #find itTenPrint"Find Numbers", Dataset[mid]) OneElif Dataset[mid] >Find_num: # Find the number on the left of mid APrint"\033[31;1m Find the number in mid[%s] left \033[0m"%Dataset[mid]) -             returnBinary_search (dataset[0: Mid], find_num) -         Else: # Find the number on the right of mid thePrint"\033[32;1m Find the number in mid[%s] to the right \033[0m"%Dataset[mid]) -             returnBinary_search (dataset[mid+1:],find_num) -     Else: -         ifdataset[0] ==find_num: #find it +Print"We got the numbers.", dataset[0]) -         Else: +Print"No, the number you're looking for [%s] is not in the list ."%find_num) A   at   -Binary_search (data, the)

5. Anonymous functions

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

#这段代码def Calc (n):     return n**nprint (calc= lambda n:n**nprint (calc)

6. Introduction to Functional programming

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.

Functions in functional programming the term does not refer to a function in a computer (actually a subroutine), but rather to a function in mathematics, the mapping of an independent variable. This means that the value of a function is determined only by the value of the function parameter, not by other states. For example, the sqrt (x) function calculates the square root of X, as long as x is not changed, and whenever the call is called, the value is constant.

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

First, the definition

Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.

The main idea is to write the operation process as much as possible into a series of nested function calls. For example, there is now a mathematical expression:

(1 + 2) * 3-4

Traditional procedural programming, which may be written like this:

var a = 1 + 2;

var B = A * 3;

var c = b-4;

Functional programming requires the use of functions, which can be defined as different functions, and then written as follows:

var result = Subtract (multiply (add), 3), 4);

This code evolves the following and can be turned into this

Add. Multiply (3). Subtract (4)

This is basically the expression of natural language. Look at the following code, you should be able to understand its meaning at a glance:

Merge ([1,2],[3,4]). Sort (). Search ("2")

As a result, the code for functional programming is easier to understand.

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

1 def Add (x,y,f): 2     return f (x) + f (y)3  4  5 res = Add (3,-6 , ABS) 6 Print (res)

8. Built-in functions

Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii

The third week of Python's Automated development learning---basic python learning

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.