代码拉取完成,页面将自动刷新
# 调用函数
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)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。