author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/81
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .
Function can improve the modularity of application , And code reuse . You already know Python Many built-in functions are provided , such as print(). But you can also create your own functions , This is called a user-defined function .
You can define a function that you want to function , Here are the simple rules :
Python Define function use def keyword , The general format is as follows :
def Function name ( parameter list ):
The body of the function
By default , Parameter values and parameter names match in the order defined in the function declaration . Here is an example code ( The code can be in On-line python3 Environmental Science Run in ):
Let's use functions to output "Hello World!":
def hello() :
print("Hello World!")
hello()
More complex applications , Function with parameter variables :
def my_max(a, b):
if a > b:
return a
else:
return b
a = 4
b = 5
print(my_max(a, b))
The output of the above example :
5
Calculate the area function , Here is an example code ( The code can be in On-line python3 Environmental Science Run in ):
# Calculate the area function
def cal_area(width, height):
return width * height
def my_welcome(name):
print("Welcome", name)
my_welcome("ShowMeAI")
w = 4
h = 5
print("width =", w, " height =", h, " area =", cal_area(w, h))
The output of the above example :
Welcome ShowMeAI
width = 4 height = 5 area = 20
Define a function : Give the function a name , Specifies the parameters contained in the function , And code block structure .
After the basic structure of this function is completed , You can do this through another function call , You can also go straight from Python Command prompt execution .
The following code calls print_myself() function :
# Defined function
def print_myself( str ):
# Print any incoming strings
print (str)
return
# Call function
print_myself(" Call user-defined functions !")
print_myself(" Call the same function again ")
The output of the above example :
Call user-defined functions !
Call the same function again
stay python in , Type belongs to object , Variables have no type :
a=[1,2,3]
a="ShowMeAI"
In the above code ,[1,2,3] yes List type ,"ShowMeAI" yes String type , Variables a There is no type , It's just a reference to an object ( A pointer ), It can point to List Type object , It can also point to String Type object .
stay python in ,strings, tuples, and numbers Is an object that cannot be changed , and list,dict And so on are modifiable objects .
python Parameter passing of function :
python Everything in is the object , Strictly speaking, we can't say value passing or reference passing , We should talk about immutable objects and mutable objects .
adopt id() Function to see the memory address change :
def my_change(a):
print(id(a)) # It's pointing to the same object
a=10
print(id(a)) # A new object
a=5
print(id(a))
my_change(a)
The output of the above example is :
9788736
9788736
9788896
You can see that before and after calling the function , Formal parameter and argument point to the same object ( object id identical ), After modifying the formal parameters inside the function , Formal parameters point to different id.
The variable object modifies the parameters in the function , So in the function that calls this function , The original parameters have also been changed . Here is an example code ( The code can be in On-line python3 Environmental Science Run in ):
def change_list( mylist ):
" Modify the incoming list "
mylist.append([1,2,3,4])
print (" Value in function : ", mylist)
return
# call changeme function
mylist = [10,20,30]
change_list( mylist )
print (" Value outside the function : ", mylist)
Objects that pass in functions and add new content at the end use the same reference . So the output is as follows :
Value in function : [10, 20, 30, [1, 2, 3, 4]]
Value outside the function : [10, 20, 30, [1, 2, 3, 4]]
Here are the formal parameter types that can be used when calling a function :
The required parameters must be passed into the function in the correct order . The number of calls must be the same as when they were declared .
call print_myself() function , You have to pass in a parameter , Otherwise, there will be grammatical errors :
def print_myself( str ):
" Print any incoming strings "
print(str)
return
# call print_myself function , Without parameters, an error will be reported
print_myself()
The output of the above example :
Traceback (most recent call last):
File "test.py", line 10, in <module>
print_myself()
TypeError: print_myself() missing 1 required positional argument: 'str'
Keyword parameters are closely related to function calls , Function calls use key arguments to determine the value of the arguments passed in .
Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared , because Python The interpreter can match parameter values with parameter names .
The following example is in the function print_myself() Call with parameter name :
def print_myself( str ):
" Print any incoming strings "
print(str)
return
# call print_myself function
print_myself( str = "ShowMeAI Knowledge community ")
The output of the above example :
ShowMeAI Knowledge community
The following example code ( On-line python3 Environmental Science ) It is demonstrated that the use of function parameters does not need to use the specified order :
def print_info( name, age ):
" Print any incoming strings "
print (" name : ", name)
print (" Age : ", age)
return
# call print_info function
print_info( age=30, name="ShowMeAI" )
The output of the above example :
name : ShowMeAI
Age : 30
When you call a function , If no parameters are passed , Then the default parameters . The following code ( On-line python3 Environmental Science ) If there is no incoming age Parameters , The default value is used :
def print_info( name, age = 35 ):
" Print any incoming strings "
print (" name : ", name)
print (" Age : ", age)
return
# call print_info function
print_info( age=30, name="ShowMeAI" )
print("------------------------")
print_info( name="ShowMeAI" )
The output of the above example :
name : ShowMeAI
Age : 30
------------------------
name : ShowMeAI
Age : 35
You may need a function that can handle more arguments than it was originally declared . These parameters are called indefinite length parameters , And above 2 The parameters are different , Declaration will not be named . The basic grammar is as follows :
def function_name([formal_args,] *var_args_tuple ):
" function _ docstring "
function_suite
return [expression]
With an asterisk * The parameters of will be in tuples (tuple) The form of import , Store all unnamed variable parameters .
def print_info( arg1, *vartuple ):
" Print any incoming parameters "
print(" Output : ")
print(arg1)
print(vartuple)
# call print_info function
print_info( 100, 90, 80 )
The output of the above example :
Output :
100
(90, 80)
If no parameters are specified in the function call , It's just an empty tuple . We can also avoid passing unnamed variables to functions . The following code ( On-line python3 Environmental Science ):
def print_info( arg1, *vartuple ):
" Print any incoming parameters "
print(" Output : ")
print(arg1)
for var in vartuple:
print (var)
return
# call printinfo function
print_info( 100 )
print_info( 90, 80, 70 )
The output of the above example :
Output :
100
Output :
90
80
70
There is also a parameter with two asterisks ** The basic grammar is as follows :
def function_name([formal_args,] **var_args_dict ):
" function _ docstring "
function_suite
return [expression]
Added two asterisks ** Will be imported as a dictionary .
def print_info( arg1, **vardict ):
" Print any incoming parameters "
print(" Output : ")
print(arg1)
print(vardict)
# call print_info function
print_info(1, a=2,b=3)
The output of the above example :
Output :
1
{'a': 2, 'b': 3}
When you declare a function , Asterisk in parameter * Can appear alone , for example :
def f(a,b,*,c):
return a+b+c
If the asterisk appears alone * The parameter after must be passed in with the keyword .
def f(a,b,*,c):
return a+b+c
f(1,2,c=3) # normal
f(1,2,3) # Report errors
python Use lambda To create anonymous functions .
So called anonymity , It means to stop using def Statement defines a function in this standard form .
lambda The syntax of a function contains only one statement , as follows :
lambda [arg1 [,arg2,.....argn]]:expression
The following example :
my_sum = lambda arg1, arg2: arg1 + arg2
# call my_sum function
print (" The sum is : ", my_sum( 10, 20 ))
print (" The sum is : ", my_sum( 20, 20 ))
The output of the above example :
The sum is : 30
The sum is : 40
return [ expression ] Statement is used to exit a function , Optionally return an expression... To the caller . Without parameter value return Statement returns None. None of the previous examples demonstrated how to return a value , The following example demonstrates return Usage of sentences :
def my_sum( arg1, arg2 ):
# return 2 The sum of parameters ."
total = arg1 + arg2
print(" Within the function : ", total)
return total
# call sum function
total = my_sum( 10, 20 )
print(" Out of function : ", total)
The output of the above example :
Within the function : 30
Out of function : 30
Python3.8+ Added a function parameter Syntax / Used to indicate that the function parameter must use the specified positional parameter , Cannot use the form of keyword parameter .
In the following example , Shape parameter a and b You must use the specified positional parameter ,c or d It can be a location parameter or a keyword parameter , and e and f Keyword parameter required :
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
The following usage is correct :
f(10, 20, 30, d=40, e=50, f=60)
The following usage method will make mistakes :
f(10, b=20, c=30, d=40, e=50, f=60) # b Cannot use the form of keyword parameter
f(10, 20, 30, 40, 50, f=60) # e Must be in the form of a keyword parameter
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/vide...
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :