I. Definition Function
Recycled tools
to complete a particular function block, a function block of the storage container is
Second, the grammatical function
Function of four parts
- Based on the use of the function: function name
- Function body: completion code block
- Returns: the result of feedback functions are performed
- Parameters: complete information required function condition
To declare a function with the def keyword
def 函数名(参数们):
函数体
return '返回值'
Third, use the function
Function name: function to get the address of the
function name (): get the address of a function, and executes the code stored in the block function (function body) *****
function name (parameter): pass parameters and perform functions
Function name (): When finished, will be the return value of the function, the return value just like ordinary variables, can print directly, use, operation
def fn(num):
print("传入的num值:%s" % num)
return '收到了'
res = fn(10) # 控制台会打印:传入的num值:10 res的值为:'收到了'
Note: you must first define the function call
Fourth, the classification function
1. The parameter list is divided
No-argument function: no external resources
def start():
print('系统启动')
start()
There are function parameters: the need for a foreign key resources
def login(usr, pwd):
if usr == 'owen' and pwd == '123':
print('登录通过')
else:
print('登录失败')
login('owen', '123')
The return value is divided
return function is used to end
Empty Returns: None
def demo(x, y):
print( x + y )
def demo(x, y):
print( x + y )
return # 用来强行结束函数的(像break结束循环一样)
Single value is returned
def demo(x, y):
return x + y
Multi-value return
def demo(x, y):
return x + y, x - y, x * y, x / y # 本质就是返回装有多个值的元组
Fifth, the nested function calls
example
# 求两个数最大值
def max_2(n1, n2):
if n1 > n2:
return n1
return n2
求三个数最大值
def max_3(n1, n2, n3):
m2 = max_2(n1, n2)
return max_2(m2, n3)
求四个数最大值
def max_4(n1, n2, n3, n4):
m2 = max_2(n1, n2)
return max_3(m2, n3, n4)
Cycle call: calling another function within a function