本节主讲python函数的基本用法,主要包括传递参数、匿名函数和变量作用域。
一、传递参数
python除了传递必需参数外,还可以传递默认参数,不定长参数和关键字参数。
1. 传递必需参数
def myfunc(str) : print(str) myfunc('hello...')
hello...
2. 传递默认参数
def myfunc(name, age=30) : print('name:', name) print('age:', age) myfunc(age=25, name='xiaoming') myfunc(name='zhangsan')
name: xiaoming age: 25 name: zhangsan age: 30
3. 不定长参数
def myfunc (str, *more) : for s in more : print(s) myfunc(1, 2, 3, 4)
2 3 4
4. 关键字参数
在传递必需参数的实例中,str是python关键字
二、匿名函数 lambda
myfunc = lambda a : a + 1 print(myfunc(9))
10
三、变量作用域
total1 = 0 total2 = 0 def myfunc(a, b) : total1 = a + b global total2 #全局变量 total2 = a + b myfunc(1, 2) print(total1) print(total2)
0 3
OK, 本讲到此结束,后续更多精彩内容,请持续关注我的博客。