03_定义函数
定义函数
定义函数
关键字: def, return
def new_fib(n):
a, b = 0, 1
result = []
while a < n:
result.append(a)
a, b = b, a + b
return result
print(new_fib(100))
06_定义函数.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
定义函数详解
关键字参数
kwarg=value 形式的 关键字参数
def fun(first_str, second_str = 'hello word'):
print(first_str, second_str)
fun('nihao')
fun('nihao', second_str='word')
def fun2(first_num, second_num = 2):
print(first_num + second_num)
fun2(1)
fun2(1, 3)
06_定义函数.py
nihao hello word
nihao word
3
4
相当于给定参数默认值,有给定默认值的参数为可选参数,没有默认值的参数是必选参数,在调用函数fun()时,必须给定必选参数
**name
*name用于接收一个元组
**name 接收一个字典,用于接收除了必选参数,和可选参数外的所有参数(可以是多个)
def fun3(first_num, **other_num):
print(first_num)
for i in other_num:
print(i, ':', other_num[i])
fun3(first_num=1, second_num=2, third_num=3)
06_定义函数.py
1
second_num : 2
third_num : 3
/ 和 *
/定义位置
*定义关键字
def fun4(value_1, /, value_2, *, value_3):
print(value_1, value_2, value_3)
fun4(1, 2, value_3=3)
/ 必须在 *前面
浙公网安备 33010602011771号