def function_name(arg1,arg2): # Define a function with def start ,
#function_name For function name , In letters 、 The beginning of the underscore can be followed by an alphanumeric underscore , The function name can reflect the task performed by the function .( Case sensitive )
#(arg1,arg2) For function parameters , But one 、 Two or no . When calling a function, you can pass the function .
function body # Function content , To indent
return value # Function return value , The value returned after the function is executed , It can also be regarded as returning... Without returning any value none.
# example
del introduce(name):
print("hello",name)
introduce('woeld')
# Call the function once , Will be output
hello world
# Must function
del f1(a,b):
print("a+b",a+b)
add(1,2)
add(1)# error
add(1,2,3)# error
# Key function
del f2(name,age):
print(" full name :",name)
print(" Age ",age)
f2(" Xiao Ming ",18)
f2(age=18,name=" Xiao Ming ")
# The default function
del f3(name,age=18):
print(" full name :",name)
print(" Age ",age)
f3(" Xiao Ming ")# Default age=18
f3(" Xiao Ming ",19)
# Variable parameters
del f4(*args):
print(args)
f4()
f4(1,2)
f4(" Xiao Ming ",18)# Get tuple
del f5(**kwargs):
print(kwargs)
f5()
f5(name=" Xiao Ming ")# Get the dictionary
The scope of a variable is the namespace of the variable
del f(x):
print(y)
return x
return y
print(x)# error
print(y)# error
a=1
del f1(a):
a=2
print(a)# Output a=1
del f2(a):
global a
a=2
print(a)# Output a=2
Get the local variables of the function body , You can use return return
Anonymous functions , There is no need to define the function name
lambda The expression is to use the parameter and return value of a function “:” separate , The meaning is the same as function , It can be assigned to a variable .
It is generally used for functions that are used only once 、 Take function as parameter in function
def add(x,y):
return x+y
# amount to
f=lambda x,y:x+y
Built in functions filter, Used to filter sequences , Filter non-conforming elements . The first parameter needs to upload a function as the filter condition , The second parameter is the sequence to be filtered .
a=[1,2,3,4,5,6,7,8]
b=[x for x in filter(lambda x:x>5,a)
print b# Will be output [6,7,8]
The first line of the function body can be a string , This string is the document string . It's usually """ “”"
The document string can be used _doc_ obtain
Function annotations are defined as follows :
def function_name(a:expression,b:expression)->expression:
function body
return value
use : To annotate parameters , use -> To annotate the return value