A custom function syntax structure:
def fun1 ([X],[y],....):
Statement 1
Statement 2
Use the def statement to define the function, write the function name, parentheses, arguments (none), colon, and then indent the function body after def
1. No parameter function:
def test ():
print ' This is a function without parameters '
Test ()
2. Functions with Parameters
def test1 (x, y): #x, Y is the parameter (access provided to the user)
Print x * y
Test1 (2,3) #调用时称为实参
3. Functions with parameters with return values
Def test2 (A, B):
Print a
Print B
c = A + b
Return C
sum = test2 (3,5) # If the function has a return value, the call is required to have a variable to store the return value
Print sum
4. Return multiple values with parameters -- Returns a tuple (multiple variables receive a tuple at the same time)
Def test3 (A, B):
Print a
Print B
c = A + b
D = A * b
E = A/b
Return c,d,e
result = Test3 (6,3)
Print result
Example: Game move recoil punctuation return
def move (x,y,step,angle=0):
NX = x + step * Math.Cos (angle)
NY = y-step * Math.sin (angle)
Return Nx,ny
ZB = Move (100,100,60,MATH.PI/6)
Print ZB
5. Predefined values for functions (default parameters)
def test4 (x,y,z,h=4):
Print X
Print Y
Print Z
h = x + y + z + H
Return h
sum = test4 (+/-)
Print sum
def test5 (h=4,x,y,z)-Error, when there is a predefined value parameter, this parameter can only be placed in the last
Example: the n-th side of x:
def power (X,n):
s = 1
While n > 0:
n = n-1
s = S * x
return s
Print power (3,4)
When there are multiple predefined values, you can either reset the predefined values in order or do not set them in order
The only difference is that you need to add the parameter name when you do not set it in order, such as:
def student (name,gender,age=8,city= ' Shenzhen '):
print ' name is: ', name
print ' Gender is: ', gender
print ' Age was: ', age
print ' city was: ', city
Student (' James ', ' M ', 7)
Student (' Polo ', ' M ', city= ' Guangzhou ')
Python basic 11-Function Custom function