day3 python 函数
常犯的错误:
IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行...
函数是指一组语句的集合通过一个名字(函数名)封装起来,执行这个函数,调用这个函数名即可。
特性:
减少代码重复
使程序变得可扩展性
使程序易维护
#定义函数
def sayhi(): #函数名
print ('hello world')
sayhi()#调用函数
f=open('yesterdate.txt','a') f.truncate(44) #截取长度
#文件的修改 f=open('../dang.txt','r') #源文件 p=open('yesterdat.txt','w') #没有文件创建文件,修改的内容写入新文件里 #replace修改文件内容 for line in f: if "i like code but really you" in line: line=line.replace("i like code but really you","i like code but fulimei you") p.write(line) f.close() p.close()
#这个用sed就可以了:
#sed -i 's/version=.*/version=0/' config.ini
#如果有多个ini文件:
#sed -i 's/version=.*/version=0/' *.ini
#位置参数 def calc(x,y): print(x) print(y) calc(1,2) #关键字参数 def test(x, y): print(x) print(y) test(y=3,x=4)
def ff(x,y): print(x) print(y) a=9 b=8 ff(y=a, x=b)
位置参数与形参一一对应
关键字参数与形参顺序无关
关键字参数不能写在位置参数前面
*args 元组 接受位置参数 ,不能接收关键字参数
**kwargs 字典
def test1() : print('in the test1') def test2() : print ('in the test2') return 0 def test3() : print ('in the test3') return 0 ,'hello',['zhang','xin'],{'tt':'aaa'} x=test1() y=test2() z=test3() print (x) print (y) print (z)
----------------------------
注释很多行#,CTRL+A 然后再ctrl +/
TRL+A 然后 ctrl+d 复制下所有内容
name=['zba','dex','ggg'] def calc(name): name[0]="女王" print(name) calc(name) print(name)
预期结果
['女王', 'dex', 'ggg']
['女王', 'dex', 'ggg']
#递归
def cu(n): print(n) if int(n/2) >0: return cu(n/2) print(n) cu(10)
# python 或 批处理 替换文件中的内容
# 有一个配置文件 config.ini 其中有一段内容 "version=x" 此处x为0、1、2、3、4等数字,但不确定是什么数字 # 如何将这段内容替换为“version=0” 要是用批处理实现是最好的,应该会用到通配符, # 用批处理实现起来有难度。
import re f1 = r'd:config.ini' f2 = r'd:config.ini.1' with open(f2, 'w') as ff2: with open(f1, 'r') as ff1: for x in ff1: if 'version=' in x: x = re.sub(re.search('version=(d+)', x).group(1), '0', x) ff2.write(x)