The function will be ⼀ paragraph Have unique ⽴ function Code block for , Integrate to ⼀ individual whole And name , Where needed transfer ⽤ This name can complete the corresponding requirements . Function in the development process , Can be more ⾼ Realization of efficiency Code heavy ⽤.
def Function name ( Parameters ):
Code 1
Code 2
Function name ( Parameters ): Call function
demand 1: Making calculators , Calculate the sum of any two numbers , And save the results
def sum_num(a,b):
return a+b
result = sum_num(1, 2)
print(result)
(1) documentation : If there's a lot of code , We don't need to find the location of this function definition in a lot of code to see the comments . If you want to be more ⽅ It is convenient to check the operation of the function ⽤, You can use the function documentation .
(2) Nested functions use : Another function is nested in one function .
If the function A in , transfer ⽤ In addition ⼀ A function B, So let's start with the function B All tasks in ⾏ After that, we will return to the last function A Of board ⾏ The location of .
demand 2: Print multiple horizontal lines
def print_line():
print('-'*20)
def print_lines():
i=0
while i<=10:
print_line()
i+=1
print_lines()
(3) Variable scope : Local and global variables
effect : Inside the body of the function , Save data temporarily , That is, when the function is called ⽤ After completion , Destroy the local variable .
myth :
No . Because line 15 gets a The data is still 100, Global variables are still defined a The value at the time of , There is no return value , Instead of returning testB intra-function 200. Sum up ,testB Internal a=200 It just defines a local variable .
How to modify a global variable inside a function body :
(4)return:return a, b When returning multiple data , The default is tuple type .return after ⾯ You can connect to the list 、 Tuple or dictionary , To return multiple values .
(5) Multi function execution process :
def user_info(name, age, gender):
print(f' What's your name {
name}, Age is {
age}, Gender is {
gender}')
user_info('Rose', age=20, gender='⼥')
user_info('⼩ bright ',gender=' male ',age=16)
note: A function ⽤ when , If there are position parameters , The positional parameter must precede the keyword parameter ⾯, But there is no order between keyword parameters .
name Refers to the variable name , Without quotes .
Sum up , Whether it is package location transfer or package keyword transfer , It's all a packaging process .
# Unpacking element group
def return_num():
return 100, 200
num1, num2 = return_num()
print(num1)# 100
print(num2)# 200
# Unpacking dictionary
dict1 = {
'name':'TOM', 'age':18}
a, b = dict1# Enter the dictionary ⾏ unpacking , What comes out is the dictionary key
print(a)# name
print(b)# age
print(dict1[a])# TOM
print(dict1[b])# 18
c=a
a=b
b=c
a,b=1,2
a,b=b,a
print(a)
print(b)
stay python in , Values are passed by reference .( Data is passed through variables ) We can ⽤id() To determine whether the two variables are the same ⼀ A reference to a value ⽤. We can id Value is understood as the address identification of that memory .
# 1. immutable : int type
a = 1
b = a
print(b)# 1
print(id(a))# 140708464157520
print(id(b))# 140708464157520
a = 2# Because of the modification a The data of , Memory needs to open up another space for storage
print(b)# 1, explain int The type is immutable
print(id(a))# 140708464157552, At this point, we get the number of yes 2 Memory address of
print(id(b))# 140708464157520
# 2. list
aa = [10, 20]
bb = aa
print(id(aa))# 2325297783432
print(id(bb))# 2325297783432
aa.append(30)
print(bb)# [10, 20, 30], The list is of variable type
print(id(aa))# 2325297783432
print(id(bb))# 2325297783432
References as arguments :
def test1(a):
print(a)
print(id(a))
a += a
print(a)
print(id(a))
# int: Before and after calculation id Values are different
b = 100
test1(b)
# list : Before and after calculation id Same value
c = [11, 22]
test1(c)
Data can go directly into ⾏ modify , If you can modify it directly, it is variable , Otherwise, it is an immutable type
characteristic : The function itself calls itself + There must be an exit
# 3+2+1
def sum(i):
if i==1
return 1
return i+sum(i-1)
Application scenarios : A function has a Return value , And only A code , It can be used Lambda simplify
lambda parameter list : expression
(1) Use Lanbda Expressions compare to functions , It can simplify the memory occupied by code
(2)Lambda Parameters of can be ⽆, The parameters of the function lambda It is completely suitable in the expression ⽤.
(3)lambda Function can accept any number of arguments, but can only return ⼀ The value of an expression
fn2=lambda:100
print(fn2)# Print directly Lambda expression , The output is the memory address ( Anonymous functions )
print(fn2())# Call with no arguments
fn3=lambda a,b:a+b
print(fn3(1,2))
print((lambda a,b:a+b)(1,2))
# No arguments
print((lambda:100)())
# One parameter
print((lambda a:a)('hello'))
# Default parameters
print((lambda a,b,c=100:a+b+c)(10,20))
# Variable parameters : Accept variable length position parameters , Return a tuple
print((lambda *args:args)(10,20,30))
# Accept variable length keyword parameters , Return dictionary
print((lambda**kwargs: kwargs)(name='python', age=20))
# Judge
fun=lambda a.b:a if a>b else b
print(100,22)
# List data according to the dictionary key Value to sort
students = [{
'name':'TOM', 'age':20},'name':'ROSE','age':19},{
'name':'Jack','age':22}
# Press name Values in ascending order
students.sort(key=lambda x: x['name'])
print(students)
# Press name Values in descending order
students.sort(key=lambdax: x['name'],reverse=True)
print(students)
hold function As another function Parameters The incoming programming mode is called higher-order function , Higher order function is the embodiment of functional programming , Is a highly abstract form of programming .
# Find the absolute value
abs(-10) # 10
def add_num(a, b):
return abs(a) +abs(b)
result = add_num(-1, 2)
print(result)# 3
def sum_num(a, b, f):
return f(a) + f(b)
result = sum_num(-1, 2, abs)
print(result)# use f Instead of abs
Functional programming ⼤ Quanshi ⽤ function , Reduced code duplication , So the program ⽐ Shorter , Faster development .
Store the function in a file called modular In a separate document , Then import the module into the main program .import Statement allows the code in the module to be used in the currently running program file .
(1) Create a module :
(2) Import specific functions
(3) Use as Give the function an alias
(4) Use as Assign an alias to a module
(5) Import all functions of the module
Module positioning sequence :
Dangdao ⼊⼀ A module ,Python The search order of the parser for the module location is :
1. At present ⽬ record
2. If not at present ⽬ record ,Python Search in shell Variable PYTHONPATH Each of the following ⽬ record .
3. If you can't find ,Python Will look at the default path .UNIX Next , The default path ⼀ General /usr/local/lib/python/
The module search path is stored in system Modular sys.path variable . Variable ⾥ Contains the current ⽬ record ,PYTHONPATH And the default... Determined by the installation process ⽬ record . Be careful ⾃⼰ Of ⽂ The part name should not be duplicate with the existing module name , Otherwise, the function of the module will fail ⽆ French envoy ⽤ send ⽤from Module name import function
When , If the function name is repeated , transfer ⽤ To the final definition or derivation ⼊ The function of .
If ⼀ A module ⽂ There are __all__ Variable , When to make ⽤from xxx import * guide ⼊ when , Can only lead to ⼊ The elements in this list .
The package organizes the associated modules in ⼀ rise , That is, put it in the same place ⼀ individual ⽂ Clip down , And in this ⽂ Clip creation ⼀ The first name is __init__.py⽂ Pieces of , So this ⽂ The clip is called a bag .
demand :
Into the ⼊ The system displays the system function boundary ⾯, Function as follows :
(1) Add students
(2) Delete student
(3) Modify student information
(4) Query student information
(5) Display all student information
(6) Exit the system
System total 6 Features ,⽤ Household basis ⾃⼰ Demand selection .
step :
1. Show the functional world ⾯
2.⽤ Households lose ⼊ Function serial number
3. according to ⽤ Households lose ⼊ Function serial number of , Of board ⾏ Different functions ( function )
# The function function is to operate students , The information of each student is stored in a dictionary ,
# Storing all student information should be a global variable list
info=[]
# Display function
def print_info():
print('-'*20)
print(' Welcome to the student management system ')
print('1: Add students ')
print('2: Delete student ')
print('3: Modify student information ')
print('4: Query student information ')
print('5: Display all student information ')
print('6: Exit the system ')
print('-'*20)
# Add student information
def add_info():
new_id=input(" Please enter the student number ")
new_name=input(" Please enter a name ")
new_tel=input(" Please enter your mobile number ")
global info# Declare global variables
for i in info:
if new_name==i['name']:
print(" The user already exists ")
return
info_dict={
}
info_dict["id"]=new_id
info_dict["name"]=new_name
info_dict["tel"]=new_tel
info.append(info_dict)
print(info)
# Delete student information
def del_info():
""" Delete student """
while True:
del_id = int(input(' Please lose ⼊ Student ID to delete :'))
global info
# Check if the delegates are present
# If it exists, delete the data of the specified subscript in the list
if 0<= del_id<len(info):
del_flag = input(' Are you sure you want to delete ?yes or no')
if del_flag == 'yes':
del info[del_id]
print(info)
break
# Deleted ⽬ Exit the cycle after marking the student information
else:
print(' transport ⼊ The student made a mistake , Please re-enter ⼊')
def modify_info():
""" Modify student information """
while True:
modify_num = int(input(' Please lose ⼊ Student ID to be modified :'))
global info
# Check if this student exists , Print student information if it exists , And press ⽤ Households lose ⼊ modify
if 0<= modify_num<len(info):
print(f' The student number of the student is {
info[modify_num]["id"]}, Name is {
info[modify_num]["name"]},⼿ The number is {
info[modify_num]["tel"]}')
info[modify_num]["id"] = input(' Please lose ⼊ Student number :')
info[modify_num]["name"] = input(' Please lose ⼊ full name :')
info[modify_num]["tel"] = input(' Please lose ⼊⼿ immediately :')
print(info)
break
else:
print(' transport ⼊ The student made a mistake ')
def search_info():
""" Query student information """
search_name = input(' Please lose ⼊ The name of the student to find :')
for i in info:
if search_name == i['name']:
print('*** The query information is as follows ***')
print(f' The student number of the student is {
i["id"]}, Name is {
i["name"]},⼿ The number is {
i["tel"]}')
break
else:print(' check ⽆ this ⼈......')
# User input function
while True:
print_info()
user_num=int((input(" Please enter the function number ")))
if user_num == 1:
add_info()
elif user_num == 2:
del_info()
elif user_num == 3:
modify_info()
elif user_num == 4:
search_info()
elif user_num == 5:
print(' Student number \t full name \t⼿ immediately ')
for i in info:
print(f'{
i["id"]}\t{
i["name"]}\t{
i["tel"]}')
elif user_num == 6:
exit_flag = input(' Are you sure you want to quit ?yes or no')
if exit_flag == 'yes':
break
else:
print(" The input function is incorrect ")