Python基础---Task05:函数与Lambda表达式
函数
built-in functions 内置函数
python3 内置函数定义及用法查询
http://docs.python.org/3/library/functions.html
bin(-10) # 转二进制
>> '-0b1010'
dir() # 返回当前模块的所有函数名
自定义函数
- 函数定义并不会执行函数体;只有当函数被调用时才会执行此操作
- 空函数可作占位符,若还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来
创建函数
def my_function1(x): # 注意勿漏':'
if not isinstance(x,str):
raise TypeError('bad operand')
#参数检查:当输入的变量类型不是str时,输出Type: bad operand
if(x=='psycopath'):
print('Charles,Alice,Eva and Coco')
return 1 #最好定义返回值
my_function1(1)
def null_fun(): # 定义空函数,可执行
pass
函数闭包和返回值
函数只能返回一个数据结构,可以是序列,可迭代对象或函数
1.由参数完整度决定返回值
# 输出坐标(x,y)
def fun1(x):
print('fun2 have got x coodinate ')
def fun2(y):
#fun2是一个闭包,而且闭包内可直接使用外层变量,不用传入
print('fun2 have got x&y coodinates ')
return x,y
return fun2 # 第1层函数返回fun2函数
x = 23.6
y = 11
coordinate = fun1(x)
coordinate(y) # coordinate可分次获得参数
print(coordinate)
# 分次获得参数返回内嵌函数
>> fun2 have got x coodinate
fun2 have got x&y coodinates
<function fun1.<locals>.fun2 at 0x00000222A2201488>
coordinate = fun1(x)(y)
print(coordinate)
# 一次性获得参数返回闭包值
>> fun2 have got x coodinate
fun2 have got x&y coodinates
(23.6, 11)
2.函数返回多值时,实际是返回一个tuple
'''计算一元二次方程的解'''
import math
def quadratic(a, b, c): #定义函数
delt = b**2-4*a*c
if(delt>=0):
# 实根
x1 = ( (-b + math.sqrt(delt) )/( 2 * a )) ###注意注意注意:多项式除法一定要加()
x2 = ( (-b - math.sqrt(delt) )/( 2 * a ))
# 注意运算符顺序,用()
else:
# 虚根
x1 = -b/(2*a) ,'+',math.sqrt(4*a*c-b**2)/(2*a),'i'
x2 = -b/(2*a) ,'-',math.sqrt(4*a*c-b**2)/(2*a), 'i'
return x1,x2
a,b,c = map(float,input('pleast input a,b,c:').split(','))
# map(fun,seq):把fun,依次作用于seq
# split把输入的字符串以','分割,并存成[],按序赋给a,b,c
x1, x2 = quadratic(a,b,c) # x1,x2分别拿到两根
print('ax^2 + bx + c =0的两根:','x1=',x1,'\n','x2=',x2)
>> pleast input a,b,c:1,2,3
>> ax^2 + bx + c =0的两根: x1= (-1.0, '+', 1.4142135623730951, 'i')
x2= (-1.0, '-', 1.4142135623730951, 'i')
argument实参和parameter形参
argument即C语言中的global variable全局变量,parameter即C语言中的local variable局部变量
位置参数和默认参数
def list1(name,gender,city=‘Shanghai’): … 中
name,gender,age是位置参数,初始化时按位赋值
city 是默认参数,初始化时不用设置
def list1(name,gender,age,city='Shanghai'): #name~city 都是parameter
'这是函数文档,帮助使用者了解该函数作用' #函数文档,方便使用者查看
real_name = 'Eva' # real_name是 local variable
global real_name
real_name = 'Eva' # 声明修改全局变量
print('name:',real_name,'\n','gender:',gender,'\n','age:',age)
real_name = 'Charles' #real_name是glabal variable
list1(real_name,age = '30', gender = 'male') #real_name是位置argument,
print(list1,'\n',real_name) # 局变覆盖全变,但不改变全变
>> name: Eva
默认参数在定义时就固定了地址
def list2(L = []): #让默认参数L指向固定内存[]
#argument是工人的便笺(无内存),位置argument是空便笺,
#默认argument是指明笺(指向一个固定内存),
L.append('more')
print(L)
#运行fun时只给位置argument赋值,及运行缩进块
list2() #第一次往这个固定[]加入'more'
list2() #L仍指向def时固定内存,此时这个内存因为上面的命令已存入一个'more',这是第二次加入'more'
>> ['more']
['more', 'more']
可变参数
#输入n个数计算它们的平方和
def list3(*number): #'*'表示()里的值会以tuple形式给number
sum = 0
formula = '0^2'
print(number)
for i in number:
sum = sum + i**2 #**表示运算符——幂次方
formula = formula + '+' + str(i) +'^2'
print(formula,'=',sum)
return 1
list3(1,2,3,4)
#虽然输入4个数但以(1,2,3,4)形式给了number(前加*),仍是一个参数拿一个值
list3()
>> (1, 2, 3, 4)
0^2+1^2+2^2+3^2+4^2 = 30
()
0^2 = 0
关键字参数
def expanded_list( name, age, **dict): #**dict为keyword argument,*表示()从第三个位置开始往后的所有值都以{}形式传入
print('name:', name, 'age:', age, dict)
expanded_list('Charles', 30, gender = 'Male', position = 'First accessory personality')
#当keyword argument 的位置有多个默认argument时,keyword argument 生成一个{}
extra = {'name': 'Alice', 'gender': 'Female', 'position': 'Second accessory personality'}
expanded_list('Alice', 17, gender=extra['gender'], position = extra['position']) #dict['key']表示key对应的内容
#keyword argument才可用dict赋值
##4.named keyword argument
def list(name, gender, *,position):
print(name, gender, position)
return 1
list(**extra)
#list中所有的named keyword argument 都可以用包含关键字的{}传入,条件:形参里有‘*,’,在dict前要加**
#若命名关键词参数已赋值,作为传入的{}中就不能有相同的关键词,否则会报错
>> name: Charles age: 30 {'gender': 'Male', 'position': 'First accessory personality'}
name: Alice age: 17 {'gender': 'Female', 'position': 'Second accessory personality'}
Alice Female Second accessory personality
Lambda表达式
用于创建匿名函数,格式:
lambda : 返回值
temp = lambda x,y : x + y # 求两数和
print(temp(1,2))
print(type(temp)) # temp为函数
>>3
<class 'function'>
反思
教程顺序:鱼C/python语言程序设计—>pythoncookbook—>python官方文档
小甲鱼零基础学习python
https://www.bilibili.com/video/av4050443
python官方文档
https://docs.python.org/zh-cn/3/reference/compound_stmts.html#function
6 days