1.函数的理解和定义
def print(self, *args, sep=' ', end='\n', file=None):
def min(*args, key=None):
def 函数名():
函数体
- 定义一个函数
在没有调用函数的情况下,函数是不会被执行的
def hello(): ##定义函数
print('hello')
print('hello')
hello() ##调用函数
- 函数里面嵌套函数
def fentiao():
print('is fentiao....')
def westos():
print('westos')
westos()
fentiao()
- 形参与实参
def func1(a): #定义函数时的变量称为形式参数,变量名可以任意起(a为形式参数)
name = 'westos'
print('hello %s' %(a))
func1(12) #调用函数时的参数称为实参,该参数必须是实际存在的(12为实参)
func1('linux')
func1('python')
2.函数的动态添加
def fun():
print(fun.x)
fun()
# 动态添加
fun.x = 3
fun()
# 动态删除
del fun.x
fun()
3.函数的返回值
函数调用时一般有返回值,没有定义返回值的时候,python中默认返回None
def hello():
print('hello')
res = hello()
print(res) ##函数即输出hello也输出None
#正确表达:
def hello():
return 'hello' # return 返回的表达式或者变量
res = hello()
print(res)
4.多个返回值
def fun(a):
# 接收一个列表,求这个列表的最大值,平均值,最小值
max_num = max(a)
min_num = min(a)
avg_num = sum(a)/len(a)
# python函数中,只能返回一个值
# 如果非要返回多个值,会把返回的值封装为一个元组数据类型
return max_num,min_num,avg_num
variables = fun([34,1,2,3,4,5,6,7,421])
print(variables,type(variables))
5.函数形参之四大参数类型
参数:形参 实参
形参的分类:位置参数 默认参数 可变参数 关键字参数
- 位置参数:形参和实参必须保持一致
def getInfo(name, age): # 按照位置传递参数 print(name, age) getInfo(age=18, name='name')
- 默认参数:形参和实参可以不一致
def mypow(x,y=2): """ 求x的y次方 :param x: :param y: :return: """ print(x**y) mypow(4) ##默认y=2 mypow(4,3) ##x=4,y=3
- 可变参数
def mySum(*args): """ 需求:用户可以传递任意的值,计算数值的和 *args:是一个可变参数 args:是元组数据类型 :param args: :return: """ print(args) sum = 0 for item in args: sum += item print(sum) mySum(1,2,3,4,5,6,7,8) nums = [1,2,3,4,5,6] nums1 = (2,5,6,7,9,10) nums2 ={1,2,3,4,5,6,7,8} mySum(*nums2)
- 关键字参数
def getStuInfo(name,age,**kwargs): print(name,age) print(kwargs) getStuInfo('westos',11,hobbies=['code','running'],gender='female')
另:
score = (12,23,56,78,90)
minscore,*middlescore,maxscore = score
print(*middlescore) ##输出:23 56 78
print(middlescore) ##输出: [23, 56, 78]
如果要对字典进行解包,一个星号:获取key值
d = dict(a=1,b=2)
print(*d) ##输出: a b
getStuInfo('westos',11,**d) ## **d输出字典
6.函数的作用域
- 作用域
局部作用域
全局作用域
- 全局作用域:作用于整个程序
num = 10
print('out fun: id=',id(num))
- 局部作用域,在函数运行时生效,函数运行结束则释放
num =2
num = 10
print('out fun: id=',id(num))
def fun():
print('in fun:id=',id(num))
print('in fun:num = %s' %(num))
fun()
print('out fun: num=%s' %(num))
num = 10
def fun():
# 通过global关键字声明局部变量为全局变量
# 函数执行完毕,变量依然生效
global num
num = 2
fun()
print(num) ##输出:2
7.参数检测
def add(x, y):
if isinstance(x, (int, float)) and isinstance(y, (int, float)):
return x + y
else:
print('Error:')
res = add(2.5,2)
print(res)