One 、 Function basis
Two 、 Function parameter
3、 ... and 、 Function return value
Four 、 Function nested call
5、 ... and 、 practice
What is a function : A series of Python The combination of sentences , You can run one or more times in a program ,
It usually completes specific independent functions
Why use functions :
Maximize code reuse and minimize redundant code , The overall code structure is clear , Problem localization
Function definition :
def Function name ():
The body of the function [ A series of python sentence , Represents an independent function ]
Function call :
In essence, it is to execute the code block in the function definition , Before calling the function Must be defined first
Hold down ctrl To function , You can see the comments of the function itself ( The premise is to write notes )
\\ The escape character is '\'
# print(' Xiao Zhang's height is %f'%1.73)
# print(' Xiao Zhang's weight is %f'%160)
# print(' Xiao Zhang's hobby is %s'%' Sing a song ')
# print(' Xiao Zhang's height is %s'%' Computer information management ')
# Process other logical information
# Print out small pieces of information many times
print('--------------- Output the same information multiple times ---------------------')
# print(' Xiao Zhang's height is %f'%1.73)
# print(' Xiao Zhang's weight is %f'%160)
# print(' Xiao Zhang's hobby is %s'%' Sing a song ')
# print(' Xiao Zhang's major is %s'%' Computer information management ')
# For the above scenario You need to further optimize the code 【 programme : Packaging function 】
# Definition of function
# def Function name ( parameter list ):0-n individual
# Code block
def printInfo():
'''
This function is used to print personal information It is a combination of small pieces of information
:return:
'''
# Function code block
print(' Xiao Zhang's height is %f' % 1.73)
print(' Xiao Zhang's weight is %f' % 160)
print(' Xiao Zhang's hobby is %s' % ' Sing a song ')
print(' Xiao Zhang's major is %s' % ' Computer information management ')
pass
# Function call
# printInfo() # Function call
# printInfo() # Multiple calls
# printInfo()
# printInfo()
# printInfo()
# print(' I'm another code block ...')
# Further improve such needs 【 Output information about different people 】 programme : Solve the problem by passing in parameters
def printInfo(name,height,weight,hobby,pro): # Formal parameters
# Function code block
print('%s His height is %f' %(name,height))
print('%s My weight is %f' %(name,weight))
print('%s My hobby is %s' %(name,hobby))
print('%s My major is %s' %(name,pro))
pass
# Call the information with parameters
printInfo(' petty thief ',189,200,' Play the game ',' consultant ') # Actual parameters
print('------------------ Call with parameters ---------------------------')
printInfo('peter',175,160,' Code code ',' Computer application ')
# Classification of parameters :
# Required parameters 、 Default parameters [ Default parameters ]、 Optional parameters 、 Key parameters
# Parameters : In fact, a function is to realize a specific function , Then, in order to get the data needed to realize the function
# In order to get the of external data
# 1 Required parameters
def sum(a,b): # Formal parameters : Just a parameter in the sense of , When defining, it does not occupy the memory address
sum=a+b
print(sum)
pass
# Function call You must select a parameter when calling Must be assigned
# sum(20,15) #20 15 The actual parameter : Actual parameters , Real parameters , Is the actual memory address
# sum(15) # It can't be written like this ,
# 2: Default parameters 【 Default parameters 】 Always at the end of the parameter list
# def sum1(a,b=40,c=90):
# print(' The default parameter is =%d'%(a+b))
# pass
# # Default parameter call
# sum1(10) # If it is not assigned at the time of calling , It will use the default value given when defining the function
# sum1(2,56)
# Variable parameters ( When the number of parameters is uncertain, use , More flexible
# def getComputer(*args): # Variable length parameters
# # '''
# # Calculate the cumulative sum
# # :param args: Variable length parameter type
# # :return:
# # '''
# # # print(args)
# # result=0
# # for item in args:
# # result+=item
# # pass
# # print('result=%d'%result)
# # pass
# #
# # getComputer(1)
# # getComputer(1,2)
# # getComputer(1,2,3)
# # getComputer(1,2,3,4,5,6,7,8)
# Keyword variable parameters 0-n
# ** To define
# In the body of the function The parameter keyword is a dictionary type key Is a string
def keyFunc(**kwargs):
print(kwargs)
pass
# call
# keyFunc(1,2,3) Non transitive
dictA={"name":'Leo',"age":35}
# keyFunc(**dictA)
# keyFunc(name='peter',age=26,)
# keyFunc()
# The use of combinations
# def complexFunc(*args,**kwargs):
# print(args)
# print(kwargs)
# pass
# # complexFunc(1,2,3,4,name=' Lau Andy ')
# complexFunc(age=36)
# def TestMup(**kwargs,*args): # Not in conformity with the requirements
# '''
# Optional parameters must be placed before keyword optional parameters
# Optional parameters : The accepted data is a tuple type
# Keyword optional parameters : The accepted data is a field type
# :param kwargs:
# :param args:
# :return:
# '''
# pass
# Function return value
# Concept : After the function is executed, it will return an object , If there is... Inside the function return You can return the actual value , Otherwise return to None
# type : Can return any type , The type of return value should depend on return The latter type
# purpose : Return data to the caller
# There can be more than one... In a function body return value : But you can only return one return
# If in a function body Yes return, It means that the function is executed and exits ,return The following code statements will not execute
def Sum(a,b):
sum=a+b
return sum# Return the calculated result to
pass
# rs=Sum(10,30) # Assign the return value to other variables
# print(rs) # The return value of the function returns to the place where it was called
def calComputer(num):
li=[]
result=0
i=1
while i<=num:
result+=i
i+=1
pass
li.append(result)
return li
pass
# Call function
# value=calComputer(10)
# print(type(value)) #value type
# print(value)
def returnTuple():
'''
Return data of tuple type
:return:
'''
# return 1,2,3
return {"name":" test "}
pass
A=returnTuple()
print(type(A))
Functions can be called nested , That is to call another function inside one function , The inner function can access the variables defined in the outer function , But it can't be reassigned (rebind)
# Nested function
def fun1():
print("--------------fun1 start-------------------")
print("-------------- Execute code omission -------------------")
print("--------------fun1 end-------------------")
pass
def fun2():
print("--------------fun2 start-------------------")
# Call the first function
fun1()
print("--------------fun2 end-------------------")
pass
fun2() # Call function 2
# Classification of functions : According to the return value of the function and the parameters of the function
# With parameters and no return value
# With parameters and return values
# No parameter and return value
# No parameter, no return value
# ---------------------- Homework 1 ---------------------
# receive n A digital , Find the sum of these parameters
def sum(* args):
sum = 0
for item in args:
sum += item
pass
return sum
pass
A = sum(1,2,3,4,5)
print(A)
# ---------------------- Homework 2 ---------------------
# Find the number of the incoming list or tuple as the corresponding element , And return to a new list
def func(con):
'''
Process list data
:param con: What you receive is a list or tuple
:return: The new list object is returned
'''
li = []
index = 1
for i in con:
if index%2==1: # Judge odd digits
li.append(i)
pass
index += 1
pass
return li
B = func([1,2,3,4,5])
C = func({'1':'a', '2':'b', '3':'c'})
D = func(tuple(range(10, 30)))
print(B)
print(C)
print(D)
# ---------------------- Homework 3 ---------------------
# Check each of the incoming dictionaries value The length of , If more than 2, Keep the first two , And return the new content to the caller
# PS: In the dictionary value It can only be a string or a list
def dictfunc(dicParms): # **kwargs or dicParms
'''
Processing dictionary type data
:param kwargs: Dictionaries
:return:
'''
result = {} # An empty dictionary
for key, value in dicParms.items(): # key-value
if len(value)>2:
result[key] = value[:2] # Add data to the dictionary
pass
else:
result[key] = value
pass
return result
dictobj = {'name':' Ouyang ', 'hobby':[' Sing a song ',' dance ',' motion ',' Programming '], 'pro':' art '}
E = dictfunc(dictobj)
print(E)