2 Star 3 Fork 3

celaraze / learning-python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
8.函数.py 1.85 KB
一键复制 编辑 原始数据 按行查看 历史
绯末 提交于 2019-12-27 11:30 . 补全函数;增加切片
# 调用函数
abs(200)
abs(-10)
abs(12.3)
# 定义函数
def my_abs(x):
if(x >= 0):
return x
else:
return -x
# 空函数
# pass什么都不做,作为占位符
def nop():
pass
# 返回多个值
# 返回多个值实际就是返回了一个元组
def run(distance, speed):
distance = distance * 100
speed = speed * 10
return distance, speed
# 接收多个返回值
d, s = run(100, 10)
# 默认参数
# 默认参数必须指向不变对象
def runTwo(distance, speed=10):
distance = distance*100
speed = speed*10
return distance, speed
# 可变参数
# 会把传入的参数自动转为列表或者元组,变量前面加*
def calc(*numbers):
for number in numbers:
print(number)
# 调用可变参数的函数
calc(1, 2, 3, 4, 5, 6, 7)
# 关键字参数
# 把传入的参数自动转为字典,变量前面加**
def runThree(distance, speed, **props):
print(distance, speed, props)
# 调用关键字参数的函数
runThree(1000, 100, color='red', quality='good')
# 在关键字参数中检查是否存在指定的参数
def runFour(distance, speed, **props):
if 'color' in props:
# 如果有color参数,则此处执行代码
pass
if 'quality' in props:
# 如果有quality参数,则此处执行代码
pass
print(distance, speed, props)
# 限制关键字参数的函数
# 用*分隔,*后面的参数名就是可被传入的参数,此时别的参数传入将无效
def runFive(distance, speed, *, color, quality):
print(distance, speed, color, quality)
# 递归函数
# 计算机中,递归函数是通过栈数据结构实现的,每当进入一个函数调用,栈就增加一层栈帧,每当函数返回,栈就会减少一层栈层
# 栈不是无限的,递归调用过多,会导致栈溢出
def fact(n):
if n == 1:
return 1
return n*fact(n-1)
Python
1
https://gitee.com/celaraze/learning-python.git
git@gitee.com:celaraze/learning-python.git
celaraze
learning-python
learning-python
master

搜索帮助