函数的作用 | |
---|---|
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()
方式查看内置函数用法
#函数基本结构
def funcanme(parameter_list):
pass
#4个空格缩进
def | funcanme | (parameter_list) | : |
---|---|---|---|
关键字定义函数 | 函数名称 | 参数列表 | 冒号 |
#实现两个数字相加
#打印输入的参数
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,所有返回Nonedef 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)
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'>
a = 1
b = 1
c = 1
as
a =b =c =1
as
a, b, c =1, 1, 1
#输出
1 1 1
def add(x, y)
result = x + y
return result
c = ddd(y=3, x=2)
#用 c 记录调用 add 函数的过程,关键字参数,明确指定 形参 赋值
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 = '光明小学')
#错误写法,必须参数和默认参数不可混用