全局变量和局部变量
a = 200 #全局变量
def dcs():#定义函数
a = 100 #局部变量
print(a)#打印局部变量 100
dcs()#调用函数
print(a)#打印全局变量 200
函数体中有变量则优先引用函数中的变量
如果函数体中没有变量则引用函数体外的全局变量
全局变量 可以被任何函数方法引用
局部变量 只能被当前函数本身来引用(如需要用可以用函数传递)
把局部变量变为全局变量
a = 200 #全局变量
def dcs():#定义函数
global a #把函数中的局部变量声明为全局变量
a = 100 #局部变量
print(a)#打印局部变量 100
dcs()#调用函数
print(a)#100
函数传递
def dcs1():#定义函数
a = 100 #局部变量
return a #返回值 把具体的结果赋予给函数时就需要此方法
def dcs2():#定义函数
#d=dcs1()#函数传递 第一种方式
c= 50 #局部变量
#c +=d
c +=dcs1() #函数传递 第二种方式
print(c)#150
dcs2()
def dcs1():#定义函数
a =100 #局部变量
c =a/2 #除法
return c #50 返回
def dcs2():
d=dcs1() #函数传递
d *=2 #乘法
return d #返回
print(dcs2())#100
format格式化输出
#默认顺序输出
print('{}{}'.format('hello','duoceshi'))#helloduoceshi
#设置指定索引位输出
print('{1}{0}'.format('hello','duoceshi'))#duoceshihello
#设置参数输出
print('{c}{a}'.format(a='hello',c='duoceshi'))#duoceshihello
#对字典进行格式化输出
d={'name':'多测师','url':'www.duoceshi.com'}
c='公司名称{name},网址{url}'.format(**d)
print(c)#公司名称多测师,网址www.duoceshi.com
zip 函数
list1=['name','age']
list2=['laowang',18]
list3=list(zip(list1,list2))#通过zip函数打包后,用list函数转换为列表输出
print(list3)#[('name', 'laowang'), ('age', 18)]
#如果没有对应的值则不会进行打包
print(dict(list3))#{'name': 'laowang', 'age': 18}转换为字典
open函数
open() 函数用于打开一个文件,创建一个 file对象
语法pen(file, mode),模式有r(只读),w(写入覆盖),a(写入追加)
open('D:\test1\aa.txt')#路径有错误
open('D:/test1/aa.txt')#第一种方法直接将\改为/
open(r'D:\test1\aa.txt')#第二种方法在前面加上r
#读取文件,r 表示读
a=open('D:/test1/aa.txt','r',encoding='utf-8')
#python默认的编码格式gbk,文件编码默认是utf-8,所以需要更改格式
# a1=a.read()#读取文件中的所有内容
# print(a1)# 打印结果test1test2test3
# a2=a.readline()#读取文件中的第一行内容
# print(a2)#test1
a3=a.readlines()#读取文件全部内容返回一列表
print(a3)#['test1\n', 'test2\n', 'test3']
追加a
a=open('D:/test1/aa.txt','a',encoding='utf-8')
n= '\n18班都是万元户'#(\n表示换行)
a.writelines(n)#追加内容
覆盖w
a=open('D:/test1/aa.txt','w',encoding='utf-8')
n= '武汉18班都是万元户'
a.writelines(n)#替换掉文件中所有内容
|
|