目录
- Functions
- `1. 简介`
- 1.1 `无参数无返回值`
- 1.2 `有参数无返回值`
- 1.3 `有参数有返回值`
- `2. 函数参数``
- `3. 函数文档`
Functions
1. 简介
1.1 无参数无返回值
def fuc():
print('hello world!')
fuc() # hello world!
1.2 有参数无返回值
def fuc(str):
print(f'hello {}!')
fuc('world') # hello world!
1.3 有参数有返回值
def fuc(str):
return f'hello {}!'
print(fuc('world')) # hello world!
`2. 函数参数``
- 无默认值
- 无默认值参数必须赋值,参数赋值顺序与函数定义时参数顺序一致
def my_fancy_calculation(first, second, third):
return first + second - third
print(my_fancy_calculation(3, 2, 1)) # 4
# 指定参数赋值
print(my_fancy_calculation(first=3, second=2, third=1)) # 4
- 给参数加上默认值
- 有默认值参数可以不赋值,此时该参数为默认值
- 有多个有默认值参数时,可以指定参数进行赋值,否则值会赋值给其它参数
def my_fancy_calculation(first, second=2, third=1):
return first + second - third
print(my_fancy_calculation(3, third=1)) # 4
- 不要将可变参数作为参数默认值,且在函数中尽量不要修改其值,否则会导致函数不能正常执行功能
3. 函数文档
- 定义函数时,在第一行用3引号对函数的功能入参、返回进行描述
- 使用help查看函数文档,jupyter中可使用函数+??查看函数源码
def calculate_sum(val1, val2):
"""This is a longer docstring defining also the args and the return value.
Args:
val1: The first parameter.
val2: The second parameter.
Returns:
The sum of val1 and val2.
"""
return val1 + val2
print(help(calculate_sum))