Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of the function developed by Python full stack

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The purpose of this article is to share with you about the usefulness of Python full-stack development functions. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Introduction to No.1 function

The so-called function is to organize a block of code with independent functions into a small module, which can be called when needed.

There are two steps to using the function:

1. Define the function

2. Call the function

The function of function, code reuse, improve development efficiency

The format of the No.2 definition and call definition function is as follows: def function name (): code encapsulated by the function

Def is the abbreviation of define.

The function name should be able to express the function of encapsulating the code of the function, which is convenient for subsequent calls.

The naming of function names should conform to the naming rules of identifiers.

Function call:

The function can be called through the function name ().

No.3 normal parameter def func (name): # name is the formal parameter print (name) # function body func ('kernel') # executes the function, and' kernel' is the default parameter of the argument No.4

After the default parameter is defined, it is no longer needed to be passed in when the function is called, and the default parameter is placed at the end

Def info (name,age,country='China') # name,age is a normal parameter, and country is the default parameter print ('name:',name) print (' age:',age) print ('country:', country) info ('kernel',21) # when country is not passed in, the default parameter No.5 key parameter is used

Normally, parameters need to be passed to the function in the defined order, and the key parameters must be used if you don't want to, but the key parameters must be placed after the normal parameters.

Def info (name,age,country='China') # name,age is a common parameter, and country is the default parameter print ('name:',name) print (' age:',age) print ('country:', country) info (age=21,name='kernel') # using key parameters, you can unpack No.6 elements and dictionaries out of order

* args

Def demo (* args): print (args) # ('kernel', 21,' Shandong') demo ("kernel", 21, "Shandong")

* * kargs

Def demo (* * kwargs): print (kwargs) # {'name':' kernel', 'age': 21,' address': 'Shandong'} demo (name= "kernel", age=21,address= "Shandong") No.7 recursive function

Features:

The function calls itself internally

The code inside the function is the same, but the parameters are different and the processing results are different.

When the parameter satisfies a condition, the function no longer executes

Chestnut 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): 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: # the number found is on the left side of mid print ("number found on the left side of mid [% s]"% dataset [mid]) return binary_search (dataset [0: mid]) Find_num) the number found by else:# is on the right side of mid print ("the number found is on the right side of mid [% s]"% dataset [mid]) return binary_search (dataset [mid + 1:], find_num) else: if dataset [0] = = find_num: # find it print ("numbers found", dataset [0]) else: print ("No points") The number [% s] you are looking for is not in the list the variable and immutable parameters of the "% find_num) binary_search (data,66) No.8 function

In a function, will the use of assignment statements for parameters affect the arguments when the function is called?

No, as long as you use an assignment statement for a parameter, whether it is a mutable type or an immutable type, the reference of the parameter will be modified in the function and will not affect the reference of external variables.

Def demo (num, num_list): print ("start") # assignment statement num= 200 num_list= [4 id 5 num 6] print ("id=%d,num=%d"% (id (num), num) print ("id=", id (num_list), "num_list=", num_list) print ("end") gl_num=100 # id=1875081376,gl_num=100gl_list = [1Mei 2Mei 3] # id= 2164478175240 gl_list [1PM 2] 3] print ("id=%d,gl_num=%d"% (id (gl_num), gl_num) # id=1875084576,num=200print ("id=", id (gl_list), "gl_list", gl_list) # id= 2164477982152 num_list= [4,5,6] demo (gl_num, gl_list) print ("id=%d,gl_num=%d"% (id (gl_num), gl_num) # id=1875081376,gl_num=100print ("id=", id (gl_list), "gl_list" Gl_list) # id= 2164478175240 gl_list [1,2,3]

If the passed parameter is a mutable type, inside the function, the content of the data is modified using the method, which will also affect the external data.

Def demo (name_list): name_list.append ('end') print (name_list) name_list = [' kernel'] print ("id=", id (name_list), "name_list", name_list) # id= 1980496082376 name_list ['kernel'] demo (name_list) print ("id=", id (name_list), "name_list", name_list) # id= 1980496082376 name_list [kernel',' end'] demo (name_list) print ("id=") Id (name_list), "name_list", name_list) # id= 1980496082376 name_list ['kernel',' end' 'end'] We found that the data of external variables had been changed. But its reference has not changed. Look at another chestnut def demo (name_list= []): name_list.append ('end') print (name_list) demo () # [' end'] demo () # ['end',' end'] demo () # ['end',' end', 'end'] demo () # [' end', 'end',' end' [end'] this is not what we want. What are we going to do? We just need to change the parameter to an immutable type def demo (name_list=None): name_list= [] name_list.append ('end') print (name_list) demo () # [' end'] No.9 higher order function

It can be called a higher order function if one of the following conditions is satisfied.

There is a parameter as a function

There is a function in the return value of the function

Map function

The map function is a high-order function built into Python. It takes a function and an iterable object, acts the function on each element of the iterable object, and returns a map object.

Def func (x): return x * xr = map (func,range (10)) print (list (r)) # [0,1,4,9,16,25,36,49,64,81] reduce function

The reduce function is also a high-order function built into Python. Similarly, it receives a function and an iterable object, but the function must receive two parameters. Reduce calls the function on each object of the iterable object and returns the final result.

Chestnut 1from functools import reducedef func (xQuery y): return x * yr = reduce (func,range (1Magne 10)) print (r) call procedure func (1Power2), 3), 4), 5), 7), 8), 9) Chestnut 2from functools import reducedef func (xMague y): return x * yr = reduce (func,range (1d10)) 10) print (r) calls procedure func (1) 10), 2), 3), 4), 5), 7), 8), 9) filter function

The filter function is also a high-order function built into Python. Similarly, it receives a function and an iterative object. The function of the function is to judge each element, return True and False,filter, and automatically filter out elements that do not meet the criteria according to the result of the judgment.

Def func (x): if x% 2 = = 0: return xr = filter (func,range (10)) print (list (r)) lambda function

No function name

Single statement

The result of the execution of the statement is the return value

Name_list = ['kernel','alex','qiyue','hobby','eric','aomikee'] r = sorted (name_list) print (r) r = sorted (name_list,key=lambda x:len (x)) print (r) No.10 function closure

Internal function

Def outer (): print ('outer is running.') Def inner (): print ('inner is running.') Inner () outer () outer is running. Inner is running . The inner function inner exists in the scope of the outer function, so if you call the inner function outside the outer area, you will get an error.

On closures

Def outer (): X = 10 y = 10 def inner (): print (x function) return innerfun = outer () fun () # 20 if you try to reference a variable of an external function in an internal function, this is the Python closure. Because the closure is based on the internal function, the closure cannot be called externally either.

Modify the variables of an external function

Def outer (): X = 10 y = 10 def inner (): X = x + 1 print (xroomy) return innerfun = outer () fun () # UnboundLocalError: local variable'x 'referenced before assignment

Because the closure is based on the internal function, the masking mechanism of the Python interpreter will be started. At this time, the Python interpreter thinks that x is a local variable of the internal function. We are just trying to modify the variables that do not exist, so we report a reference error before the definition. So, how to solve this problem?

Python2

If the variable of the external function scope is mutable, then it will not be blocked by the Python interpreter def outer (): X = [10] y = 10 def inner (): X [0] = x [0] + 1 print (x [0] + y) return innerfun = outer () fun () # 21

Python3

Use the nonlocal keyword def outer (): X = [10] y = 10 def inner (): nonlocal x x = x + 1 print (x _ scopy) return innerNo.11 scope block scope

Think about whether the following program will run successfully? Why?

For i in range (10): passprint (I) # 9 code executed successfully. In strongly typed languages such as Java/C#, executing the above language indicates that I is not defined, but it can be executed in Python, because there is no block-level scope in Python, variables in the code. External can call local scope def say_hello (): name = 'kernel' print (' hello', name) print (name) # NameError: name' name' is not defined run error, name variable only plays a role in the function, so the global is not callable scope chain

There is a domain chain in Python. First of all, look for it from your own scope. If you don't have it, go to the upper level, and report an error if you don't find it.

Name = "Alex" def f1 (): name = "Eric" def f2 (): name = "Kernel" print (name) f2 () F1 () # Kernel Chestnut name = "kernel" def f1 (): print (name) def f2 (): name = "eric" f1 () f2 () # Kernel Why enter Kernel instead of eric? That's because the scope chain has already been formed when the function is not executed, so F1 will go to the global variable to find the variable name instead of f2R = ([lambda: x for x in range (10)]) print (type (r)) for i in r: print (type (I)) print (I ()) returns a list type, each element of the list is a function, and all functions run out to be 9, why? That is because the internal code will not be executed when the function is not executed. thank you for reading! This is the end of this article on "what is the use of the full stack development function of Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report