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 :
By default , Parameter values and parameter names match in the order defined in the function declaration .
Here is a simple Python function , It takes a string as an incoming parameter , Then print it to the standard display device .
Defining a function only gives 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 Prompt execution .
The following example calls printme() function :
# Defined function
defprintme(str):
“ Print any incoming strings ”
printstr
return
# Call function
printme(“ I'm going to call user defined functions !”)
printme(“ Call the same function again ”)
The output of the above example :
I'm going to 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=“Runoob”
In the above code ,[1,2,3] yes List type ,"Runoob" yes String type , Variables a There is no type , She's just a reference to an object ( A pointer ), It can be List Type object , You 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 .
Immutable type : Variable assignment a=5 After the assignment a=10, This is actually a new generation of int The value object 10, let a Pointing to it , and 5 To be discarded , Not change a Value , It's equivalent to a new generation of a.
Variable type : Variable assignment la=[1,2,3,4] After the assignment la[2]=5 Will be list la The third element value of changes , In itself la Didn't move , Only part of its internal value has been modified .
python Parameter passing of function :
Immutable type : similar c++ Value transfer of , Such as Integers 、 character string 、 Tuples . Such as fun(a), It's just a Value , No impact a Object itself . For example fun(a) Internal modification a Value , Just modify another copied object , Does not affect the a In itself .
Variable type : similar c++ By reference , Such as list , Dictionaries . Such as fun(la), Will be la Really pass it on , After modification fun External la It will also be affected
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 .
defChangeInt(a):
a = 10
b = 2
ChangeInt(b)
printb# The result is 2
In the case of int object 2, The variable that points to it is b, Pass on to ChangeInt Function time , The variables are copied as values b,a and b All point to the same Int object , stay a=10 when , Then a new int The value object 10, And let a Pointing to it .
# Write function description
defchangeme(mylist):
“ Modify the incoming list ”
mylist.append([1,2,3,4])
print" Value in function : ", mylist
return
# call changeme function
mylist = [10,20,30]
changeme(mylist)
print" Value outside the function : ", mylist
The object passing in the function and adding new content at the end of the instance 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 necessary parameters must be passed in the correct order into the function . The number of calls must be the same as when they were declared .
call printme() function , You have to pass in a parameter , Otherwise, there will be grammatical errors :
# Write function description
defprintme(str):
“ Print any incoming strings ”
printstr
return
# call printme function
printme()
The output of the above example :
Traceback (most recent call last): File "test.py", line 11, in <module> printme() TypeError: printme() takes exactly 1 argument (0 given)
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 printme() Call with parameter name :
# Write function description
defprintme(str):
“ Print any incoming strings ”
printstr
return
# call printme function
printme(str = “My string”)
The output of the above example :
My string
The following example can show more clearly that the order of key parameters is not important :
# Write function description
defprintinfo(name, age):
“ Print any incoming strings ”
print"Name: ", name
print"Age ", age
return
# call printinfo function
printinfo(age=50, name=“miki”)
The output of the above example :
Name: miki Age 50
When you call a function , If the value of the default parameter is not passed in , Is considered the default value . The following example will print the default age, If age Not passed in :
# Write function description
defprintinfo(name, age = 35):
“ Print any incoming strings ”
print"Name: ", name
print"Age ", age
return
# call printinfo function
printinfo(age=50, name=“miki”)
printinfo(name=“miki”)
The output of the above example :
Name: miki Age 50 Name: miki 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 :
deffunctionname([formal_args,] *var_args_tuple): " function _ docstring "function_suitereturn[expression]With an asterisk (*) The variable name of will hold all unnamed variable parameters . Examples of indefinite length parameters are as follows :
# Write function description
defprintinfo(arg1, *vartuple):
“ Print any incoming parameters ”
print" Output : "
printarg1
forvarinvartuple:
printvar
return
# call printinfo function
printinfo(10)
printinfo(70, 60, 50)
The output of the above example :
Output : 10 Output : 70 60 50
python Use lambda To create anonymous functions .
lambda The syntax of a function contains only one statement , as follows :
lambda [arg1 [,arg2,.....argn]]:expression
The following example :
# Write function description
sum = lambdaarg1, arg2: arg1 + arg2
# call sum function
print" The sum is : ", sum(10, 20)
print" The sum is : ", sum(20, 20)
The output of the above example :
The sum is : 30 The sum is : 40
return sentence [ expression ] Exit 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 next example tells you how to do :
# Write function description
defsum(arg1, arg2):
# return 2 The sum of parameters ."
total = arg1 + arg2
print" Within the function : ", total
returntotal
# call sum function
total = sum(10, 20)
The output of the above example :
Within the function : 30
Not all variables of a program can be accessed in any location . Access depends on where the variable is assigned .
The scope of the variable determines which specific variable name you can access in which part of the program . The two most basic variable scopes are as follows :
Variables defined within a function have a local scope , Define a global scope outside the function .
Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope . The following example :
total = 0# This is a global variable
# Write function description
defsum(arg1, arg2):
# return 2 The sum of parameters ."
total = arg1 + arg2# total Here is the local variable .
print" Function is a local variable : ", total
returntotal
# call sum function
sum(10, 20)
print" Outside the function is the global variable : ", total
The output of the above example :
Function is a local variable : 30 Outside the function is the global variable : 0