python3 不定长参数传递实例
局部变量
school = 'oldboy edu' names = ['alex', 'jack', 'rain'] names_tuple = (1,2,3,4) name = 'alex' age = 22 # def change_name(): # # names[0] = '金角大王' # name = '金角大王2' # print('inside func', names) # print('inside func', name) # # change_name() # print(names) # print(name) def change_name2(name): global school#修改全局变量 school = 'mage linux' print('before change', name, school) name = 'Alex Li'#局部变量作用域 age = 23 print('after change', name) print('school:',school) name = 'alex' change_name2(name) print(name) print('age:', age) print('school', school)
参数传入
def test(x,y,z): print(x) print(y) print(z) # test(y=2,x=1) #与形参顺序无关 # test(1,2) #与形参一一对应 #test(x=2,3) test(3,z=2,y=6)
递归
def calc(n): print(n) if int(n/2)>0: return calc(int(n/2)) print('->',n)
高阶函数
def add(a, b, func): return func(a)+func(b) res = add(1, -6, abs) #函数位置传入内加求绝对值函数 print(res)
文件操作
import sys fobj = open('yesterday2', 'r', encoding='utf-8') fobj_now = open('yesterday2.bak', 'w', encoding='utf-8') find_str = sys.argv[1] replace_str = sys.argv[2] for line in fobj: if find_str in line: line = line.replace(find_str, replace_str) fobj_now.write(line) fobj.close() fobj_now.close()
不定长参数传入
1 # *args:接收N个位置参数,转换成元组形式 2 3 # def test(*args): 4 # print(args) 5 # 6 # test(1,2,3,4,5) 7 # test(*[1,2,3,4,5]) 8 # 执行时args = tuple([1,2,3,4,5]) 9 10 # def test1(x,*args): 11 # print(x) 12 # print(args) 13 # 14 # test1(1,2,3,4,5,6,7) 15 16 # **kwargs:接收N个关键字参数,转换成字典方式 17 18 # def test2(**kwargs): 19 # print(kwargs) 20 # print(kwargs['name']) 21 # print(kwargs['age']) 22 # print(kwargs['sex']) 23 # 24 # test2(name='alex', age=8, sex='male') 25 # test2(**{'name':'alex', 'age':'22', 'sex':'male'}) 26 27 def test3(name, **kwargs): 28 print(name) 29 print(kwargs) 30 31 test3('alex',age=8, sex='male') 32 33 def test4(name, age=18, *args, **kwargs): 34 print(name) 35 print(age) 36 print(args) 37 print(kwargs) 38 logger('TEST4') 39 40 def logger(source): 41 print('from %s' % source) 42 43 test4('alex', age=34, sex='male',hobby='tesla')