List of articles

• 11.1 abs() and round() function
• 11.2 Built in higher order function （map、reduce、filter）
• 9.1 Use of functions
• 9.2 Function documentation
• 9.3 Nested calls to functions
• 9.4 Scope of variable
• 9.5 Function return value （ Multiple return values ）
• 9.6 The type of the argument to the function
• 9.7 Quote as argument
• 9.8 Summary of variable and immutable types
• 9.9 Recursive functions and anonymous functions （lambda）
• 8.1 List derivation
• 8.2 Dictionary derivation
• 8.3 Set derivation
• 8.4 Deductive summary
• 7.1 Operator
• 7.2 Public methods
• 7.3 Container type conversion
• Preface
• 7. Public operation
• 8. The derived type
• 9. Python function
• 10. Student management system

Preface

1. stay Python Basics （ One ） in , Thank you very much 、 Collection 、 Comment on 、 Focus on .
2. stay Python Basics （ Two ） in , Try to sort out the knowledge points in a concise and easy to understand way .
3. If it's helpful for your study , Give me a thumbs up , One button, three links ~????

Python Basics （ One ）：https://blog.csdn.net/weixin_46818279/article/details/108576298

7. Public operation

What is public operation that ？？？

Public operation ： Data sequences basically support some operations

7.1 Operator

Operator describe Supported container types
+ Merge character string 、 list 、 Tuples
* Copy character string 、 list 、 Tuples
in Whether elements exist character string 、 list 、 Tuples 、 Dictionaries
not in Whether elements exist character string 、 list 、 Tuples 、 Dictionaries

Operator ：+（ The role of merger ）

`str1 = 'aa'str2 = 'bb'list1 = [1,2]list2 = [10,20]t1 = (1,2)t2 = (10,20)dict1 = {'name':'tom'}dict2 = {'age':30}# 1. + :  Merge print(str1+str2)      #  Output  aabbprint(list1+list2)    #  Output  [1, 2, 10, 20]print(t1+t2)          #  Output  (1, 2, 10, 20)print(dict1+dict2)    #  Report errors ： The dictionary does not support merge operations `

Operator ：*（ The replication of ）

`str1 = 'a'list = ['hello']t1 = ('world',)#   *: Copy     Support string 、 list 、 Tuples print(str1 * 5)  #  Output aaaaaprint('-' * 10)  #  Output 10 individual ----------print(list * 5)  #  Output ['hello', 'hello', 'hello', 'hello', 'hello']print(t1 * 5)    #  Output  ('world', 'world', 'world', 'world', 'world')`

Operator ：in、not in（ Determine whether an element exists ）

`str1 = 'abcd'list1 = [10,20,30]t1 = (100,200,300)dict1 = {'name':'Python', 'age':30}# in  and  not in# 1.  character a Whether there is print('a' in str1)  #  Output  Trueprint('a' not in str1)  #  Output  false# 2.  data 10 Whether there is print(10 in list1)   #  Output Trueprint(10 not in list1)  #  Output False# 3. 100 Whether there is print(100 in t1)    #  Output  Trueprint(100 not in t1)   #  Output Fasle# 4. name Whether there is print(dict1)print('name' in dict1)   # Trueprint('name' not in dict1)  # Falseprint('name' in dict1.keys()) # Trueprint('name' in dict1.values() ) # False`

7.2 Public methods

One of the public methods len()、del()、max()、min()、range(start,end,step)、enumerate()
The function and usage of these six functions , The chestnuts show that

（1）len()： Count the number of elements in the container

`str1 = 'abcd'list1 = [10, 20, 30]t1 = (100, 200, 300)dict1 = {'name':'Python', 'age':30}s1 = {10 , 20}# len()  Count the number of elements in the container print(len(str1))  #  Output 4print(len(list1)) #  Output 3print(len(t1))    #  Output 3print(len(dict1)) #  Output 2print(len(s1))    #  Output 2`

（2）del()： Delete

`str1 = 'abcd'list1 = [10, 20, 30]t1 = (100, 200, 300)dict1 = {'name':'Python', 'age':30}s1 = {10 , 20}# 1. del  The goal is   perhaps  del( The goal is )# str1 character string del str1      #  Delete the entire string print(str1)   #  An error indicates that the deletion has been successful ============================================================================# list1  list del(list1)print(list1) #  An error indicates that the deletion has been successful # del(list1[0])# print(list1)  #  Output [20, 30]# del list1[0]# print(list1)   #  Output [20, 30]==============================================================================# dict1  Dictionaries del dict1print(dict1) #  Report errors , Deleted successfully del dict1['name']print(dict1)   #   The output is  {'age': 30}==============================================================================# s1  aggregate del s1print(s1) #  Report errors , Deleted successfully `

（3）max()： Returns the maximum value of the element in the container
min()： Returns the minimum value of the element in the container

`str1 = 'abcde'list1 = [10, 20, 30]# 1. max() Maximum print(max(str1))  #  Output eprint(max(list1))  #  Output 30# 2. min(): minimum value print(min(str1))  #  Output aprint(min(list1)) #  Output 10`

（4）range()： Generated from start To end The number of , In steps of step, for for Recycling

```"""
matters needing attention ：
1.  If you don't write the beginning , The default from the 0 Start
2.  If you don't write the step size , The default is 1
"""print(range(1,10,1)) #  Output  range(1, 10), What is returned is an iteratable object , Need to cooperate with for Loop to get the numbers for i in range(1,10,1):#  Traversing iteratable objects , And get these numbers inside the object print(i)       #  The output is 1,2,3,4,5,6,7,8,9for i in range(1,10):print(i)        #  If you don't write the step size , Then the default step size is 1for i in range(1,10,2):print(i)       #  Because the step length is 2, So the output 1,3,5,7,9for i in range(10):print(i)      #  there 10 For the end . Don't write at first , The default from the 0 Start . I don't write , The default is 1.  But I can't help writing the end ！```

（5）enumerate()： Function is used to traverse a data object （ As listing 、 Tuples or strings ） Combined into an index sequence , List both data and data index , Generally used in for Cycle of .

```# 1.  grammar ： enumerate( Traversable objects ,start = 0)# 2. start Parameter is used to set the starting value of the subscript of traversal data , The default is 0list1 = ['a', 'b', 'c', 'd', 'e']# enumerate  The return result is a tuple , The first data of a tuple is the subscript corresponding to the data of the original iteration object , The second data of the tuple is the data of the original iteration object for i in enumerate(list1):print(i)'''
The output result is ：
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
'''for i in enumerate(list1,start = 1):print(i)'''
At this moment start by 1, The output result is ：
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')
'''```

7.3 Container type conversion

Go straight to the chestnuts ：

```#  The existing data type is not the same as the data type the program wants , At this time, you can use the function to do type conversion .list1 = [10,20,30]s1 = {100, 200, 300}t1 = ('a', 'b', 'c')# tuple(): Convert a sequence to a tuple print(tuple(list1))  #  The output is (10, 20, 30)print(tuple(s1))    #  The output is (200, 100, 300)# list(): Convert to list print(list(s1))      #  The output is  [200, 100, 300]print(list(t1))     #  The output is  ['a', 'b', 'c']# set(): Convert to set print(set(list1))   #  The output is {10, 20, 30}print(set(t1))      #  The output is {'c', 'b', 'a'}'''
Be careful ：
1.  Collection can quickly complete list de duplication
2.  Collection does not support subscripts （ Because there is no order ）
'''```

8. The derived type

The function of derivation ： Simplify the code

The list derivation returns a list , The dictionary derivation returns a dictionary , The set derivation returns a set

8.1 List derivation

Go straight to the code ： How derivation simplifies code , How to use derivation

```'''
Write the code ：
1.  Create an empty list
2.  The loop writes regular data to the list
Method realization :
1.  Cycle to achieve
2.  List derivation （ Simplify the code , Create or control regular lists ）
Come to the conclusion ：
1.  List derivation has the least amount of code , It simplifies the code
'''=========================================================================# while  Realization list1 = []i = 0while i < 10:list1.append(i)i += 1print(list1)  #  The output is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]==========================================================================# for  Realization #  use for Realize the comparison while The amount of code required for implementation is small list1 = []for i in range(10):list1.append(i)print(list1)   #  The output is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]==========================================================================#  List derivation implementation list1 = [i for i in range(10)]  #  The first one in brackets i, Is the return value of the received data , Then save it in the list print(list)    #  Output [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]```

Take another chestnut ： belt if List derivation of

`#  demand ：0-10 A list of even data # 1.  A simple list derivation ,range() Step size implementation list1 = [i for i in range(0,10,2)]print(list1)        #  The output is  [0, 2, 4, 6, 8]# 2. for Cycle plus if  Create a regular list list2 = []for i in range(10):if i % 2 == 0:list2.append(i)print(list2)# 3.  hold for Circular fit if Code for   rewrite   belt if List derivation of list3 = [i for i in range(10) if i % 2 == 0]print(list3)`

Another chestnut ：

```'''
demand ： The creation list is as follows ：[(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
1.  use for Loop nesting can solve
data 1：1  and  2 range(1,3)
data 2：0 1 2  use  range(3)
2.  Use the list derivation to solve ： many for The list derivation of is equivalent to for A nested loop , It's just punctuation 、 Carriage returns and indents .
'''# 1.  use for A nested loop list1 = []for i in range(1,3):for j in range(3):#  Add elements to the list ： Prepare an empty list before looping , Then append tuple data to the list list1.append((i,j))print(list1)   #  The output is [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]# 2.  Multiple for Implement the list derivation list2 = [(i,j) for i in range(1,3) for j in range(3)]print(list2)    #  The output is [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]```

Through these three chestnuts , I have a certain understanding of the derivation , So continue to learn the following deductive learning .

8.2 Dictionary derivation

Go straight to the chestnuts ：

`#  Create a dictionary  key yes 1-4 The number of ,value It's the square of this number dict1 = {i: i**2 for i in range(1,5)}print(dict1)  #  Output  {1: 1, 2: 4, 3: 9, 4: 16}`

Take another chestnut ： Merge list into Dictionary

```# 1.  List merge Dictionary of the same length # list1 = ['name', 'age', 'gender']# list2 = ['tom', 20, 'man']# dict1 = {list1[i]: list2[i] for i in range(len(list1))}# print(dict1)   #  The output result is  {'name': 'tom', 'age': 20, 'gender': 'man'}#  Lists of different lengths are merged into dictionaries list3 = ['name', 'age', 'gender', 'id']list4 = ['tom', 20, 'man']#  The following statement will report an error , Because of inequality , If you take a long list len(list3) May be an error # dict1 = {list3[i]: list4[i] for i in range(len(list3))}#  The following statement is correct dict2 = {list3[i]: list4[i] for i in range(len(list4))}print(dict2)   #  The output is {'name': 'tom', 'age': 20, 'gender': 'man'}'''
summary ：
1.  If two lists have the same number of data ,len Count the length of any list
2.  If the number of data in two lists is different ,len If there are too many statistical data in the list, an error will be reported ,len The number of list data with less statistical data will not be reported wrong
'''```

Another chestnut ： Extract the target data from the dictionary

```counts = {'MBP': 268, 'HP':125,  'DELL':201, 'Lenovo': 199, 'acer': 99}'''
1.  demand ： The number of extracted computers is greater than or equal to 200
Get all key value pair data , Judge v A value greater than or equal to 200 return
'''#  Returns an iterator , Inside are tuples dict_items([('MBP', 268), ('HP', 'DELL'), ('Lenovo', 199), ('acer', 99)])print(counts.items())#  Extract the target data from the dictionary , This usage is very important ！！！dict1 = {key:value for key,value in counts.items() if value >= 200}print(dict1)  # {'MBP': 268, 'DELL': 201}```

8.3 Set derivation

This one doesn't use much , A simple chestnut ：

`#  demand ： Create a collection , The data are listed below 2 Power list1 = [1,1,2]set1 = {i ** 2 for i in list1}print(set1)   #  Output  {1, 4}#  Set has data De duplication function , So this set of data has only two data , Namely 1,4`

8.4 Deductive summary

Three types of deductive writing formats

`1.  List derivation [xx for xx in range]2.  Dictionary derivation {xx1 : xx2  for ... in ...}3.  Set derivation {xx for xx in ...}`

9. Python function

Python The use of functions is similar to C、 and Java The use of functions is very much the same .

9.1 Use of functions

Basic use

```# 1.  Defined function def sel_func():print('I Love Python')# 2.  Function call print(' Congratulations on your login ')sel_func()'''
Be careful
1.  Different needs , Parameters are optional
2.  stay Python in , Functions must be defined before they are used
3.  When a function is called , The interpreter goes back to where the function is defined and executes the indented code below , When the code is finished ,
When you go back to where you called the function and continue down to define the function , The code indented inside the function body is not executed
'''```

Functions with parameters

The parameters of the function ： Function call can pass in real data , Increase the flexibility of using functions
Shape parameter ： Parameters written in function definition （ Untrue data ）
Actual parameters ： Parameters written when a function is called （ Real data ）

`#  Real data is passed in as a parameter , add #  there a、b It's a parameter def add_num2(a,b):result = a + bprint(result)# 10,20 Is the argument add_num2(10,20)  #  Output 30`

Function return The role of

```def buy():return ' smoke '# print('ok')   # This line of code does not execute goods = buy()print(goods)'''
return  effect ：
1.  Responsible for the return value of the function
2.  Exit the current function ： Lead to return All the code below （ Inside function body ） Don't execute
'''```

9.2 Function documentation

When you write your own functions , You can write a document in the function , In the future, you can directly see what the function does through this document .

```# len It's a built-in function , As early as in the definition of the time has been packaged documentation #  The function written by myself has no documentation , In order to facilitate later viewing of this explanation information, it is faster and more convenient , While defining functions , Just define a description document #  The first line of the function's internal indentation is the multi line comment written in the book . If you knock back , It will be displayed in more detail （ Parameter and return value ）.help(len)  # help Function function ： Check the documentation for the function （ The information explained by the function ）# def sum_num(a,b):#     '''  Sum function  '''  #  The documentation for defining functions #     return a + b# help(sum_num)#  Function of the advanced use of documentation .  It's just multi line comments and press enter , The parameter appears 1、2 and renturn, Explain their role .def sum_num1(a,b):'''
Sum function sum_num1
:param a:  Parameters 1
:param b:  Parameters 2
:return:  Return value
'''return a + bhelp(sum_num1)```

9.3 Nested calls to functions

Let's have a chestnut and feel it

`#  The so-called function nested call refers to the call of another function in a function #  demand ： Two functions testA  and  testB  ----  stay A Nested calls inside Bdef testB():print('B Function to -----')print(' This is a B function ')print('B End of the function -----')def testA():print('A Function to ')#  Nested calls BtestB()print('A End of the function ')testA()`

Print horizontal lines

`def print_line():print('-' * 20)#  Function nested call , Realize multiple horizontal lines def print_lines(num):i = 0while i < num:print_line()i += 1print_lines(5)`

Average any three numbers

```#   Average any three numbers # Python In language , Do division , Whether it's floating point numbers or not , As long as it's Division , The result is floating-point numbers .def sum_num(a,b,c):return a + b + c
def average_num(a, b ,c):#  Sum first , Divided by 3sumResult = sum_num(a, b, c)return sumResult / 3averageResult = average_num(1, 2, 3)print(averageResult)   #  The output is  2.0```

9.4 Scope of variable

Local access

`#  Define a function , Declare a variable ： Function body internal access , Function body external access def testA():a = 100print(a)  #  Function body internal access , Can access a Variable testA()print(a) #  Report errors ：a Variables are variables inside a function , Function cannot be accessed outside , there a Is a local variable `

Accessing global variables

`#  Declare global variables ： Functions can be accessed both inside and outside a = 100 print(a)def testA():print(a)def testB():print(a)testA()testB()`

Modify global variables

```#  Modify global variables inside functions a = 100print(a)  #  Output 100def testA():print(a)def testB():global a
a = 200print(a)testA()     #  Output 100testB()     #  Output 200print(a)    #  Output 200'''
summary ：
1.  If you put variables directly in a function a = 200 assignment , At this time a Is not a global variable modification , It's equivalent to declaring a new local variable inside the function
2.  Modify global variables inside the function body ： First global Statement a Is a global variable , And then the variables are reassigned
'''```

Multi function execution process

```# 1. Declare global variables  2.  Define two functions  3. function 1 Modify global variables ： function 2 Accessing global variables glo_num = 0def test1():global glo_num
glo_num = 100def test2():print(glo_num)
#  doubt ： Already test1 Global variables are modified in , Why the output of this place is not 100？ Because making function calls , The code inside the function body is not executed .print(glo_num)  #  The output is 0test2()  #  The output result is 0. Or because the function of the global variable is not executed test1()  #  Executed the code inside the function test2()  #  Output 100print(glo_num)  #  Output 100, because test1 The function is called , Changed global variables .```

9.5 Function return value （ Multiple return values ）

The return value is passed as a parameter

`def test1():return 50def test2(num):print(num)#  First we get the function 1 The return value of , And pass this return value into the function 2result = test1()test2(result)`

The return value of the function （ Multiple return values ）

```#  demand ： A function has two return values 1 and 2#  One if there are multiple return Not all of them , Only the first one return： It is impossible to have multiple return values for a single function # def return_num():#     return 1#     return 2## result = return_num()# print(result)  #  The output is 1. the second return It doesn't work '''
1.  The following is the correct way to write multiple return values of a function
2. return a,b How to write it , When returning multiple data , The default is tuple type
3. return You can connect the list later 、 Tuple or dictionary , To return multiple values
'''def return_num():return 1,2   #  The return value is a tuple # return  You can write tuples directly after that 、 list 、 Dictionaries 、 Return multiple values .# return (10,20)  #  The returned tuple # return [100,200]  #  Back to the list # return {'name':'Python', 'age': 20} #  The dictionary is returned result = return_num()print(result)  # return 1,2  The output is (1, 2)```

9.6 The type of the argument to the function

Positional arguments

`def user_info(name,age,gender):print(f' Your name is {name}, Age is {age}, Gender is {gender}')user_info('tom',20,' male ') #  The output is   Your name is tom, Age is 20, Gender is male #  Be careful ： The order and number of parameters passed and defined must be consistent # user_info('tom',20) #  If the number definition is inconsistent with the input, an error will be reported # user_info(20,'tom',' male ')  #  The order and definition must also be consistent , Otherwise, the data is meaningless `

Key parameters

`#  Function call , adopt " key = value " Form to be specified def user_info(name,age,gender):print(f' Your name is {name}, Age is {age}, Gender is {gender}')# 1.  Call function parameters user_info('jack', age=20 , gender=' male ')   #  Your name is jack, Age is 20, Gender is male # 2.  The keyword parameters are in sequence user_info('jack', gender=' male ', age=20)   #  Your name is jack, Age is 20, Gender is male # 3.  The positional parameter must be written before the keyword parameter # user_info(age=20 , gender=' male ', 'jack')  #  Wrong report . You have to put keywords in front of you `

Default parameters

```'''
1. Default parameters （ Default parameters ）： In order to save users' time cost , Improve user experience , You can use this parameter with default value on some requirements , Set to a default value , The parameters in this way , It's called the default parameter （ Default parameters ）.
2.  All positional parameters must appear before the default parameters
3.  When a function is called , If it is the default parameter value, modify the default parameter value ; Otherwise use this default value
'''def user_info(name,age,gender=' male '):    # gender=' male ' Is the default parameter print(f' Your name is {name}, Age is {age}, Gender is {gender}')#  No values are passed for the default parameters , Indicates use default user_info('tom', 18)  #  Your name is tom, Age is 18, Gender is male #  Pass values for default parameters , Used gender=' Woman  ', That is, the default value has been changed user_info('tom', 18, gender=' Woman ') #  Your name is tom, Age is 18, Gender is female ```

The position parameter of the variable length parameter

```'''
1. Variable length parameter is also called variable parameter . Used to determine how many parameters will be passed when calling （ It's OK not to pass it on ） Scene .
In this case, you can use package location parameter or package keyword parameter , To pass parameters .
2.  All the parameters passed in will be args Variable collection , It will be combined into a tuple based on the position of the incoming parameters ,args It's a tuple type , This is the package location transfer
'''#  Receive all position parameters , Returns a tuple def user_info(*args):print(args)#  Package location delivery #  If it is *args Receive position parameter data of variable length , It can transmit data , You can also not transfer data , Whether it's passed or not , All position parameters will be received in the future , All returned are tuples user_info()              #  ()user_info('tom')        #  ('tom',)user_info('tom', 20)     #  ('tom', 20)user_info('tom', 20,' male ')  #  ('tom', 20, ' male ')```

Keyword parameter of indefinite length parameter

`#  Collect all keyword parameters , Return a dictionary #  Package keyword delivery def user_info(**kwargs):print(kwargs)user_info()user_info(name='tom')user_info(name='tom', age=20)#  Whether it's package location delivery or package keyword delivery , It's all a packaging process `

Expand 1： unpacking

It is said that the variable length parameter is the process of packaging , Let's talk about the unpacking process

`# 1.  Unpack metagroup data # def return_num():#     return 100, 200# result = return_num()# print(result)    #  Output  (100, 200)# num1, num2 = return_num()# print(num1)   #  Output  100# print(num2)   #  Output  200# 2.  Dictionary data unpacking ： The data stored in variables is key value #  Prepare the dictionary first , Then unpack dict1 = {'name': 'tom', 'age': 20}# dict1 There are two key value pairs in , When unpacking, two variables are used to receive data a , b = dict1print(a)     #  Output nameprint(b)     #  Output age#  extract value Value print(dict1[a])     #  Output tomprint(dict1[b])     #  Output 20print(dict1['name'])  #  Output tom`

Expand 2： Exchange the values of variables

```#  Method 1：a= 10b = 20c = 0c = a
a = b
b = cprint(a)   # 20print(b)   # 10#  Method 2：a, b = 1, 2print(a)  #  Output 1print(b)  #  Output 2a, b = 1, 2a, b = b, aprint(a)  #  Output 2print(b)  #  Output 1```

9.7 Quote as argument

Experience quoting

`#  A variable is just the name of the stored data , The name can be understood as a reference to , Again python In fact, data in a language is transmitted in the form of variables #  Simple and crude understanding , A reference is a variable name . A reference can be passed into a function as an argument # 1.  Immutable type ：int# 1.1  Declare variables to hold integer data , Assign this data to another variable ：id() Check for two variables id value （ Decimal value of memory ）a = 1b = aprint(b)     #  Output 1#  Find out a and b Of id Same value print(id(a))   #  Output  140708418216784print(id(b))    #  Output  140708418216784#  modify a Data testing for id value a = 2print(b)   #  Output 1#  Because it was modified a The data of , Memory to open up another memory storage 2,id() testing a and b The address of is different print(id(a))  #  Output  140708418216816print(id(b))  #  Output  140708418216784============================================================================# 2.  Variable type ： list aa = [10, 20] bb = aaprint(bb)       # [10, 20]print(id(aa))    # 2266328490632print(id(bb))# 2266328490632#  Add data #  The list is a variable type aa.append(30)print(aa)   # [10, 20, 30]print(bb)   # [10, 20, 30]print(id(aa))  # 2266328490632   Address values print(id(bb))  # 2266328490632`

References as arguments

`def test(a):print(a)print(id(a))a += aprint(a)print(id(a))b = 100test(b)    #  This is immutable type data c = [11, 22]test(c)    #  This is variable type data `

9.8 Summary of variable and immutable types

A small summary ：

```'''
Variable types of data ： If the data is modified , It's the original data , Such data is variable type
Immutable types of data ： If the original data is not changed when the data is modified , Such data is immutable type .
Variable type ：
list
Dictionaries
aggregate
Immutable type ：
integer
floating-point
character string
Tuples

a key ：  Scope 、 Function returns multiple values 、 The parameters of the function
'''```

9.9 Recursive functions and anonymous functions （lambda）

The application of recursive function

```#  Recursive function ：1. Call yourself internally   2. There must be an exit #  Recursion is a programming idea , Function is an embodiment of programming # return It does two things : 1.  Return value  2.  Exit the current function '''
demand ：3 Add up the sum of the numbers within 3 + 2 + 1 = 6
6 = 3 + 2 Add up the sum of the numbers within
2 The cumulative sum within  = 2 + 1 The cumulative sum within
1 The cumulative sum within  = 1   #  exit
'''def sum_numbers(num):# 2. exit if num == 1:return 1# 1.  Current number  +  The sum of the current number minus one return num + sum_numbers(num - 1)result = sum_numbers(3)print(result)#  If there is no exit , Report errors ： Maximum recursion depth exceeded ```

Anonymous functions lambda, Let's have a chestnut and feel it

```'''
Application scenarios ：
1.lambda It's about simplifying the code
2. If a function has a return value , And there's only one code , have access to lambda simplify
grammar ：lambda  parameter list  ： expression
Be careful ：
lambda The parameters of the expression are optional , The parameters of the function are in the lambda It is completely applicable in the expression
lambda An expression can take more than one parameter, but it can only return the value of one expression
'''#  demand ： function   Return value 100# 1.  function # def fn1():#     return 100## result = fn1()# print(result)# 2. lambda  Anonymous functions , It's just not working def Function defined by statement . If you want to declare anonymous functions , Use lambda keyword # lambda parameter list ： expression fn2 = lambda : 100print(fn2)   # lambda Memory address # 100 Return value   Call function print(fn2())   # 100```

lambda The parametric form of

`# 1. No parameter # fn1 = lambda: 100# print(fn1())# 2.  One parameter # fn2 = lambda a: a# print(fn2('hello world'))# 3.  Default parameters / Default parameters # fn3 = lambda a, b, c = 200 : a + b + c# print(fn3(10, 20))# print(fn3(10, 20, 300))# 4.  Variable parameters ：*args# fn4 = lambda *args: args# print(fn4(10))# print(fn4(10, 20))# print(fn4(10,20,30,40))    # (10, 20, 30, 40)# 5.  Variable parameters : **kwargsfn5 = lambda **kwargs : kwargsprint(fn5(name = 'Python'))print(fn5(name = 'Python', age = 30))   # {'name': 'Python', 'age': 30}`

With judgment lambda

`# lambda application # 1. lambda  Two numbers are bigger than , Who has a big return value fn1 = lambda a, b : a if a > b else bprint(fn1(1000, 500))   # 1000`

Sort the list data

```'''
students It's a sequence name , It refers to a list sequence ,key Equal to one  lambda The expression of ,
It's used in this lambda,sort There's a parameter in it key, If there's a dictionary in the list , According to a dictionary key For sorting .
Data to be sorted in ascending or descending order in the future , This is a dictionary , Return value , The order is based on name key still age key
It's a formal parameter x It refers to all dictionaries ,
'''students = [{'name':'tom','age':20},{'name':'jock','age':21},{'name':'rose','age':22}]# 1. name key The corresponding values are sorted in descending order students.sort(key=lambda x: x['name'])print(students)# 2. age key The corresponding values are sorted in ascending order students.sort(key=lambda x: x['age'])print(students)# 3. age key The corresponding values are sorted in descending order students.sort(key=lambda x: x['age'],reverse=True)print(students)```

lambda A small summary

```'''
One 、 lambda
（1） grammar
lambda  parameter list :  expression

（2）lambda The parametric form of

No parameter :
lambda:  expression

One parameter ( Multiple parameters separated by commas ):
lambda  Parameters : expression

Default parameters :
lambda key=value: expression

Variable length position parameters :
lambda *args: expression

Variable length keyword parameter :
lambda **kwargs: expression
'''```

10. Student management system

According to what we have learned , Put the knowledge together , To do a simple student management system .

```#  Define functional interfaces def info_print():print(' Please select the function ------------------')print('1.  Add student ')print('2.  Delete students ')print('3.  Revise students ')print('4.  Ask the students ')print('5.  Show all students ')print('6.  Exit the system ')print('-' * 20)info = []#  All the functions are to operate student information , All storage of all student information should be a global variable , The data type is list .#   Function to add student information def add_info():""" Add student function """     #  Add the documentation for the function pass                 #  When we don't know what code to write inside the function body , Add one more pass Take up space ,, Avoid grammatical errors .# 1. User input ： Student number 、 full name 、 cell-phone number new_id = input(' Please enter the student number ：')new_name = input(' Please enter a name ：')new_tel = input(' Please enter your mobile number ：')# 2.  Judge whether to add this student , If the student's name already has an error message ; If the name does not exist, add data global info# 2.1  Duplicate names are not allowed ： Judge the name entered by the user   and   The dictionary in the list name The corresponding values are equal , Tips for i in info:if new_name == i['name']:print(' This user already exists ')# return effect ： Exit the current function ： Prepare an empty dictionary , Dictionary new data , Add dictionary to the list return# 2.2  If the name you entered does not exist , Add data ： Prepare an empty dictionary , Dictionary new data , Add data to the list info_dict = {}#  Dictionary new data info_dict['id'] = new_id
info_dict['name'] = new_name
info_dict['tel'] = new_tel# print(info_dict)#  Add dictionary to the list info.append(info_dict)print(info)#  Delete students def del_info():""" Delete students """del_name = input(' Please enter the name of the student you want to delete ：')global info   #  Declare global variables for i in info:      #  Traverse the list if del_name == i['name'] :#  If the name exists , Delete the data in the list info.remove(i)breakelse:        # else The role of ： When the loop ends normally, the code to be executed . Is to traverse the data in the list , Not yet break.print(' The student does not exist ！！！')print(info)#  Modify the function def modify_info():""" Modify student information """modify_name = input(' Please enter the name of the student to be modified ：')global infofor i in info:if modify_name == i['name']:i['tel'] = input(' Please enter a new mobile number ：')breakelse:print(' The student does not exist ！！！')#  Print infoprint(info)#  Query student information def search_info():""" Search for student information """search_name = input(' Please enter the name of the student you want to query ：')global info  #  Declare global variables for i in info:if search_name == i['name'] :print(' The students' information is as follows --------------------------')print(f" Student's student number ：{i['id']} ,  full name ：{i['name']},    cell-phone number ：{i['tel']}")breakelse:print(' Check no one .....')#  Show all student information def print_all():''' Show all student information '''print(' Student number \t full name \t cell-phone number ')#  Print data for all students for i in info:print(f"{i['id']}\t{i['name']}\t{i['tel']}")while True:# 1.  Display function interface info_print()# 2.  The user enters the function serial number user_num = int(input(' Please enter the function number ：'))# 3.  According to the function serial number entered by the user , Perform different functions （ function ）if user_num == 1:# print(' add to ')add_info()elif user_num == 2:# print(' Delete ')del_info()elif user_num == 3:# print(' modify ')modify_info()elif user_num == 4:# print(' Inquire about ')search_info()elif user_num == 5:# print(' Show all ')print_all()elif user_num == 6:#  Exit the system exit_flag = input(' Are you sure you want to quit ？yes or no：')if exit_flag == 'yes':break   # break Is the most important else:print(' The input function serial number is wrong ')#  This exit function , You don't need a function to do it ,1. Simple code  2. There is a necessary function , Encapsulation into functions can cause problems #  Exiting the system depends on break,break When certain conditions hold , To terminate a cycle . It's the nearest layer that stops , If you encapsulate this code #  In a function , This time with while True The cycles are not together , It's possible that something will go wrong .```

Higher order functions act on ： To simplify the code , Increase the flexibility of the function

11.1 abs() and round() function

The usage of these two functions is relatively simple , A chestnut will do it .but These two functions are not higher order functions

`# abs()  It's used to find the absolute value print(abs(-10))  # 10# round()   Rounding calculation print(round(1.2))  # 1print(round(1.6))  # 2# abs() and round() It's not a higher-order function `

11.2 Built in higher order function （map、reduce、filter）

```#  demand :  Any two numbers , Digital processing first （ Absolute or rounded ） In summation # 1.  Writing a def add_num(a,b):#  The absolute value return abs(a) + abs(b)result = add_num(-1.1, 1.0)print(result)    # 2.1# 2.  Write two def sum_num(a, b, f):return f(a) + f(b)result1 = sum_num(-1,-2,abs)print(result1)  # 3result2 = sum_num(1.2, 1.4, round)print(result2)  # 2#  The code of method two is more concise , Function flexibility is faster #  Functional programming uses a lot of functions , Reduced code duplication , So the program is shorter , Faster development '''
Higher order function ： Pass in the function as an argument , Such functions are called higher-order functions , Higher order function is the embodiment of functional programming . Functional programming is a highly abstract programming paradigm .
The purpose of higher-order functions is to simplify the code , Increase the flexibility of the function
'''```

map() function

```'''
map(func, lst), The function variable passed in func Effect to lst In each element of the variable , And make a new list of the results (Python2)/
iterator (Python3) return
'''# 1.  Prepare list data list1 = [1, 2, 3, 4, 5]# 2.  Get ready 2 A function calculated to the power of def func(x):return x ** 2# 3.  call mapresult = map(func, list1)# 4.  Acceptance results #  When printing iterators , Only the memory address can be returned , You need to use it at this time list() Convert data type print(result)     #  Output  <map object at 0x00000208211131D0>print(list(result))  # [1, 4, 9, 16, 25]```

reduce function

```'''
reduce(func, lst), among func There must be two parameters .  Every time func The result of the calculation continues to accumulate with the next element of the sequence .
Be careful : reduce() Incoming parameter func Must receive 2 Parameters
'''list1 = [1, 2, 3, 4, 5]# 1.  The import module import functools# 2. Define functional modules def func(a, b):return a + b# 3.  call reduce.  effect : The result of function calculation and the next data of the sequence are accumulated result = functools.reduce(func, list1)print(result)    #  The output is  15```

filter() function

```'''
filter(func, lst) Function to filter the sequence , Filter out the elements that do not meet the conditions , Return to one filter object .  If you want to convert to a list , have access to list() To convert
'''list1 = [1,2,3,4,5,6,7,8,9,10]# 1.  Define function : Filter even numbers in a sequence def func(x):return x % 2 == 0# 2.  call filterresult = filter(func,list1)print(result)       # <filter object at 0x000002AEA49031D0>print(list(result))      # [2, 4, 6, 8, 10]```