参考资料:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013747383144265f6402ab37cc40c5aecc816c08d8b771000
学习内容:函数
学习笔记:
1、函数定义关键字:def,举例如下:
def myFunc(a):
if a >= 18:
return True
else:
return False
print myFunc(17)
另外,Python函数支持别名方式调用,例如:
func=myFunc
print func(17)
2、函数体如果什么也不做,就使用pass关键字。例如:
def myFunc(a)
if a:
pass
else:
print 'ok'
return None
3、一个规范的函数,在执行操作之前应检查参数的有效性,并做好异常处理。例如:
def myFunc1(a):
if not isinstance(a, (int)):
raise TypeError("bad operand type, it should be an integer")
if a >= 18:
return True
else:
return False
print myFunc1('a')
4、Python函数的返回值实际上是以元组的形式存在的,因此可一次返回多个返回值。例如:
#定义了一个函数,用于根据位移和角度计算移动后的坐标值
import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
#x,y=move(100, 200, 60, math.pi / 6)
#print x,y
r = move(100, 200, 60, math.pi / 6)
print r
默认参数一定要用不可变对象,如果是可变对象,运行会有逻辑错误!例如:
def printStu(name, sex, age=6, city='Beijing'):
print "name:", name
print "sex:", sex
print "age:", age
print "city:", city
return None
printStu('test', 'F')
printStu('test1', 'F', city='Huhhot')
要注意定义可变参数和关键字参数的语法:
*args
是可变参数,args接收的是一个tuple;
可变参数既可以直接传入
,又可以先组装list或tuple,再通过
*args
传入
;例如:
def calcAdd(*x):
sum = 0
for xx in x:
sum = sum + xx
return sum
print calcAdd(1,2,3)
nums = [1, 2, 3]
print calcAdd(*nums)
**kw
是关键字参数,kw接收的是一个dict。关键字参数既可以直接传入,又可以先组装dict,再通过
**kw
传入。例如:
def printStu1(name, sex, **other):
print "name:", name
print "sex:", sex
print "other:", other
return None
printStu1('test', 'F', age=6, city='Beijing')
other={"age": 6, "city": "Beijing"}
printStu1('test', 'F', **other)
一个函数定义,可以同时具有必选参数、默认参数、可变参数和关键字参数,但顺序不能乱。例如:
def printStu2(name, sex='F', *citys, **other):
print 'name:', name
print 'sex:', sex
print 'citys', citys
print 'other:', other
return None
printStu2('test', 'F', 'Beijing', 'Huhhot', age=6)
args=('test', 'F', 'Beijing', 'Huhhot')
other={'age': 6}
printStu2(*args, **other)
6、Python支持递归函数,但存在栈溢出的问题。下面的代码可测试递归函数及栈溢出:
def fact(n):
#print "call fact(", n, ")"
if n == 1:
return 1
return fact(n - 1) * n
print fact(5)
print fact(1000) #溢出
今天就学到这里啦,下一节将学习一些Python的高级特性。