Python3 Basic Note Record-3

Source: Internet
Author: User
Tags define local variable scope

Http://www.cnblogs.com/alex3714/articles/5740985.html
The content of this section
1. Basic function syntax and features
2. Parameters and Local variables
3. Return value nesting function
4. Recursion
5. Anonymous functions
6. Introduction to Functional programming
7. Higher-order functions
8. Built-in functions

1. Basic function syntax and features
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:
Reduce duplicate code
To make the program extensible
Make programs easier to maintain
Syntax definitions
Def sayhi (): #函数名
Print ("Hello, I ' m nobody!")

Sayhi () #调用函数

can take parameters
#下面这段代码
A, B = 5,8
c = a**b
Print (c)

#改成用函数写
Def calc (x, y):
res = X**y
return res #返回函数执行结果

c = Calc (b) # result assignment to C variable
Print (c)

2. Function 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 they must have a definite value when making a function call.
To pass these values to the formal parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

Default parameters
Look at the code below
def stu_register (Name,age,country,course):
Print ("----Register student Information------")
Print ("Name:", name)
Print ("Age:", age)
Print ("Nationality:", country)
Print ("Course:", course)

Stu_register ("Wang Shanbao", "CN", "Python_devops")
Stu_register ("Zhang Jiaochun", +, "CN", "Linux")
Stu_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, it is very simple to change the country to default parameters

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.

In addition, you may have noticed that after turning the country into the default parameter, I moved the position to the last side, why?

Key parameters
Under normal circumstances, to the function of parameters to order, do not want to order the key parameters can be used, just specify the parameter name,
But remember that a requirement is that the key parameter must be placed after the positional 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 change multiple incoming parameters into a tuple form
Print (Name,age,args)

Stu_register ("Alex", 22)
#输出
#Alex () #后面这个 () is args, just because no value is passed, so it is empty

Stu_register ("Jack", +, "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", 22)
#输出
#Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is empty

Stu_register ("Jack", +, "CN", "Python", sex= "Male", province= "Shandong")
#输出
# Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}

Local variables
Code
Name = "Alex Li"

def change_name (name):
Print ("Before change:", name)
name = "Golden Horn king, a man with Tesla"
Print ("After Change", name)

Change_name (name)

Print ("Look out for name change?", name)
Output
Before Change:alex Li
After the change King King, a man with Tesla
Look outside, do you have a name change? 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:
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
If return is not specified in the function, the return value of this function is None

Forcibly inserting knowledge points: nesting letters
code example:
Name = "Alex"

Def change_name ():
Name = "Alex2"

Def change_name2 ():
Name = "Alex3"
Print ("Layer 3rd print", name)

Change_name2 () #调用内层函数
Print ("Layer 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:
10
5
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.
Stack Literacy http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html

Recursive function Practical application case, two-point search
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]

def binary_search (Dataset,find_num):
Print (DataSet)

If Len (DataSet) >1:
mid = Int (len (DataSet)/2)
If dataset[mid] = = Find_num: #find it
Print ("Find number", Dataset[mid])
Elif Dataset[mid] > Find_num: # Find the number on the left of mid
Print ("\033[31;1m the number found in mid[%s] to the left \033[0m"% dataset[mid])
Return Binary_search (Dataset[0:mid], find_num)
else:# is looking for the right number on mid.
Print ("\033[32;1m the number found in mid[%s] to the right \033[0m"% dataset[mid])
Return Binary_search (Dataset[mid+1:],find_num)
Else
If dataset[0] = = Find_num: #find it
Print ("Find numbers", dataset[0])
Else
Print ("No points, numbers to find [%s] not in list"% Find_num)


Binary_search (data,66)

5. Anonymous functions
An anonymous function is one that does not require an explicit function to be specified
#这段代码
Def calc (n):
Return N**n
Print (Calc (10))

#换成匿名函数
Calc = Lambda n:n**n
Print (Calc (10))
You may say that it is not convenient to use this thing. Oh, if it is so used, really did not improve the yarn,
But the anonymous function is mainly used in conjunction with other functions, as follows
res = map (lambda x:x**2,[1,5,7,4,8])
For I in Res:
Print (i)

6 built-in functions
Https://docs.python.org/3/library/functions.html?highlight=built#ascii
Several built-in method usage reminders
#compile
f = Open ("function recursion. Py")
Data =compile (F.read (), ', ' exec ')
EXEC (data)


#print
msg = "Back to the original starting point"
f = open ("ToFile", "W")
Print (MSG, "Your Sentimental Face in memory", sep= "|", end= "", file=f)


# #slice
# a = range (20)
# pattern = Slice (3,8,2)
# for I in A[pattern]: #等于a [3:8:2]
# Print (i)
#
#


#memoryview
#usage:
#>>> Memoryview (b ' ABCD ')
#<memory at 0x104069648>
#在进行切片并赋值数据时, you do not need to copy the original list data, you can directly map the original data memory,
Import time
For n in (100000, 200000, 300000, 400000):
data = B ' x ' *n
Start = Time.time ()
b = Data
While B:
b = b[1:]
Print (' bytes ', N, Time.time ()-start)

For n in (100000, 200000, 300000, 400000):
data = B ' x ' *n
Start = Time.time ()
b = Memoryview (data)
While B:
b = b[1:]
Print (' Memoryview ', N, Time.time ()-start)

Python3 Basic Note Record-3

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.