认识函数
print() 函数, round() 函数使用:
a = 1.23856
result = round(a, 2) #四舍五入保留两位小数
print(result)
#1.24
在命令行中查看内置函数的方法:
PS D:\python_learning> python
Python 3.6.7 (v3.6.7:6ec5cf24b7, Oct 20 2018, 13:35:33) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 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.
>>>
函数特点:
- 功能性
- 隐藏细节
- 避免编写重复的代码
函数的定义及运行特点
函数基本定义:
def funcname(parameter_list):
pass
- 参数列表可以没有
- 可以return value
简单函数的编写:
def add(x, y):
result = x + y
return result
def print_code(code):
print(code)
a = add(1,2)
b = print_code('hello python') #没有return语句时,返回None
print(a, b) #print函数可以传入多个参数来打印
#hello python
#3 None
设置系统递归的最大层数(代码一开始添加):
import sys
sys.setrecursionlimit(1000)
如何让函数返回多个结果
- 函数遇到return后结束
- 对返回类型没有要求
返回多个结果自动以元组形式返回:
def damage(skill1, skill2):
damage1 = skill1 + 3
damage2 = skill2 * 3 + 10
return damage1, damage2
damages = damage(3, 6)
print(type(damages))
#<class 'tuple'>
建议使用这种调用的方式,用有意义的名称进行解包(序列解包):
def damage(skill1, skill2):
damage1 = skill1 + 3
damage2 = skill2 * 3 + 10
return damage1, damage2
skill1_damage, skill2_damage = damage(3, 6)
print(skill1_damage, skill2_damage)
#6 28
序列解包与链式赋值
序列解包:
a,b,c = 1,2,3 #既保持精简又保证可阅读性
d = 1,2,3 #d 赋值为一个序列
print(type(d)) #<class 'tuple'>
a,b,c = d #解包,个数要相等
链式赋值
#若a =1,b= 1,c =1
a = b = c = 1
几种参数
必须参数:函数参数列表中定义的参数,必须要传递,不传递就要报错
def add (x,y): #x,y为形参
result = x + y
return result
a = add(1,2) #1和2为实参
关键字参数:可以明确指定,顺序也可以变
def add(x, y):
result = x + y
return result
c = add(y = 3, x = 2)
print(c)
#5
这两种参数的区别在于:函数的调用上
默认参数
def add (x = 1,y = 2): #默认参数,若没有设置默认参数就一定要传值进来
result = x + y
return result
- 函数定义时,形参定义要注意:必须参数全部放在默认参数之前,不可以出现混杂的情况
- 传参时:可以用关键参数标明,与默认参数结合,可以违背形参的顺序
- 默认值参数和必须参数也不能混合调用
可变参数
def demo(*param): #可变参数列表
print(param)
print(type(param))
demo(1,2,3,4,5,6) #这里不用传元组了,不然会成为二维元组
#(1, 2, 3, 4, 5, 6)
#<class 'tuple'>
传入元祖平铺:
def demo(*param):
print(param)
print(type(param))
a = (1,2,3,4,5,6)
demo(*a) #传入*a
*a的作用是把元组中元素平铺出来
可以与必须参数结合,不过必须参数要放在前面
def demo(param1,param2 = 2,*param3):
print(param1)
print(param2)
print(param3)
demo('a',1,2,3)
#a
#1 #没有办法跳过默认参数
#(2, 3)
如果可变参数放在前面,可变参数直接涵盖了后面所有的值:
def demo(param1,*param3,param2 = 2):
print(param1)
print(param3)
print(param2)
demo('a',1,2,3,'param')
#a
#(1, 2, 3, 'param') #可变参数直接涵盖了后面所有的值
#2 #默认值
(未完待续~)