目录
8-1认识函数
函数的作用
函数的作用 | |
---|---|
1 | 功能性 |
2 | 隐藏细节 |
3 | 避免编写重复的代码 |
4 | 组织代码(面向对象) |
round()
函数
ptint()
a = 1.12386
print (round(a,2))
优化后函数
#优化后函数
a = 1.12386
reslt = round(a,2)
print (reslt)
round(a,x)
为内置函数, x 为保留几位(四舍五入)
查看内置函数用法help()
>>> help(round)
Help on built-in function round in module builtins:
round(...)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
>>>
可以通过help()
方式查看内置函数用法
8-2 函数的定义及运行特点
函数基本结构
#函数基本结构
def funcanme(parameter_list):
pass
#4个空格缩进
def | funcanme | (parameter_list) | : |
---|---|---|---|
关键字定义函数 | 函数名称 | 参数列表 | 冒号 |
- 参数列表可以没有
- reture value(如果没有return,默认Value为None
函数定义举例
#实现两个数字相加
#打印输入的参数
def add(x,y)
result = x+y
return result
def print_code(code)
print(code)
a = add(1,1)
b = print_code('Python')
print (a)
print (b)
print(a,b)
#打印结果
>>>Python
3 None
- 因为在
print_code
没有定义return,所有返回None
8-3 如何让函数返回多个结果
def damage(slill1,skill2):
damage1 = skill1 * 3
damage2 = skill2 * 2 +10
return damage1, damage2
skill1_damage, skill2_damage = damage(3, 6)
#序列解包
print(skill1_damage, skill2_damage)
8-4 序列解包与链式赋值
序列解包
a = 1
b = 2
c = 3
a, b, c = 1, 2, 3
d = 1, 2, 3
print(type(d))
#序列解刨为以上过程相反 a, b, c = d
a, b, c = [1, 2, 3] #序列
d = 1 ,2 ,3
a, b, c = d
#输出
<class 'tuple'>
- d 的类型显示为一个序列
- 元素解刨元素个数要相等
链式赋值
a = 1
b = 1
c = 1
as
a =b =c =1
as
a, b, c =1, 1, 1
#输出
1 1 1
- 以上a,b, c 值都等于 1
8-5 必须参数与关键字参数
函数是Python最基本的数据单元
参数的类型
- 必须参数(必须为每个值赋值)
- 形式参数 (函数定义的过程中)
- 实际参数(调用函数的过程中,传递给参数列表 )
关键字参数(函数的调用上有所区别)
def add(x, y)
result = x + y
return result
c = ddd(y=3, x=2)
#用 c 记录调用 add 函数的过程,关键字参数,明确指定 形参 赋值
- 提高代码的可读性,不需要强制记忆函数。
8-6 默认参数
代码实例
def print_student_files(name, gender, age, college):
print('我叫' + name)
print('我今年' + str(age) + '岁')
print('我是' + gender +'生')
print('我在' + college + '上学')
print_student_files('小萌', '男', 18, '人民路小学')
使用代码默认参数
def print_student_files(name, gender='男', age='18', college='人民路小学'):
print('我叫' + name)
print('我今年' + str(age) + '岁')
print('我是' + gender +'生')
print('我在' + college + '上学')
print_student_files('小萌')
print_student_files('小乐','女',16) #更改性别,年龄
print_student_files('小明',age = 16) #只更改年龄
print_student_files('小明', age = 16, college = '光明小学') #更改年龄,学校
print_student_files('小明',gender='女', 16, college = '光明小学')
#错误写法,必须参数和默认参数不可混用
默认参数注意点
- 默认参数后不可以加非默认参数
- python 3.6