函数是一段可重复使用的代码块
函数的写法
# 用 def 定义一个函数
def lis():
print('我是函数 lis')
# 函数调用
lis()
F:\Python3.9\python.exe "D:\muyi\my python\练习.py"
我是函数 lis
Process finished with exit code 0
print 打印 return 返回值
# 用 def 定义一个函数
def lis():
return'你好'
# 函数调用
a = lis()
print(a) # 返回值 要用变量接收
lis()
print(lis()) # 返回值 可直接打印调用的函数
F:\Python3.9\python.exe "D:\muyi\my python\练习.py"
你好
你好
Process finished with exit code 0
函数的形参和实参
可以不带形参和实参
形参默认指定参数
实参指定形参
形参、实参数量和位置必须一致
# 定义一个函数
def item (x,y,z): # 形参
print(x,y,z) # 打印形参
# 调用函数
item(20,'hello','你好') # 实参
F:\Python3.9\python.exe "D:\muyi\my python\练习.py"
20 hello 你好
Process finished with exit code 0
例:
定义变量 a = 100,变量 b = 200 ,封装一个函数 user 在里面算出a+b的值
# 定义一个函数
def user (x,y): # 形参
return x+y
# 调用函数
a = user(100,200) # 实参
print(a)
F:\Python3.9\python.exe "D:\muyi\my python\练习.py"
300
Process finished with exit code 0