python基础-函数
文章目录
-
描述
- 函数是抽象的第一步
函数多是为了实现特定功能的代码的集合 需要考虑的是: 函数的参数 函数的功能 函数的返回值 python的函数 参数传递默认是引用传递- 建议不要直接修改传入对象
def my_power(x, n=2): while n > 0 a = x * a n = n - 1 return a my_power(3) -
定义函数
- 标准的定义和调用
#文档 def my_abs(x): '这是my_abs函数的文档' if x > 0: return x else return -x a = my_abs(-5) print(a) #切记写函数文档 print(my_abs.__doc__) #打印文档- 空函数
def empty_fun(): pass- 多返回值
-
函数参数
- 位置参数 默认参数
#计算1到任意值相加的和 def my_add(b=10): sum = 0 while b > 0: sum = sum + b b = b - 1 return sum my_add()- 可变参数
#传入参数的个数是可变的 比传入数组要高级 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum calc(1,2,4,3) nums = [1,2,3,4] calc(*nums) nums = (1,2,3,4) calc(*nums) #类型转换 实现可变的tuple a = (1,2,3,4) def changes(position, v, *a): b = list(a) position = int(position) b[position] = v c = tuple(b) return c c = changes(3, 5, *a) print(c) #**和*,猩猩是字典,星是元组- 关键字参数
# 传入多个含有参数名的参数 会在内部自动组装成一个字典 def person(name, age, **k): #print('name:', name, 'age:', age, 'k:', k); print('name is %s age is %d '%(name,age)) person('mengyaun', 15, city='河南', sex=1) dit = {'city'='河南', 'sex'=1} person('mengyuan', 15, **dit)- 命名关键字参数
# 可以说是对关键字参数的一种改进 添加限制不能随意传入 def person(name, age, *, city, sex): print('name is %s age is %d city is %s sex is %d'%(name,age, city, sex)) person('mengyaun', 15, city='河南', sex=1) # 如果有可变参数就不用再加* def person(name, age, *args, city, sex): print('name is %s age is %d city is %s sex is %d'%(name,age, city, sex)) #person('mengyaun', 15, city='河南', sex=1) person('mengyaun', 15, '河南', 1) # error # 可以有默认值

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论