Python学习笔记Day3
元组 tuple
创建元组
tup1 = () #创建空的元组
tup2 = (50) #<class 'int'>
tup3 = (50,)#<class 'tuple'>
print(type(tup3))
打印元组方式
tup4 = ("abc","def",2000,2000)
print(tup4[0])
print(tup4[-1])
print(tup4[1:5])
增(连接)不能直接对元组增
tupadd = (1,2,3)
#不能直接改
#tupadd[0] = 100 #TypeError: 'tuple' object does not support item assignment
tuptemp = (4,5,6)
tup = tuptemp+tupadd
print(tup)
删除 del
tuptemp = (4,5,6)
del tuptemp #删除了整个元组变量
字典 键值对
定义方式
info = {"name":"nike","age":18}
字典打印
print(info["name"])
print(info["age"])
#print(info["gender"]) #直接会报错
print(info.get("gender","m"))#没找到设置默认返回None 此语句返回m
增
info = {"name":"nike","age":18}
info["id"] = 20
print(info)
删
#删 del clear
#del info["name"] #直接删除键值对
#info.clear() #清空
改
#info["age"] = 20
查
print(info.keys())
print(info.values())
print(info.items()) #得到的所有的项(列表),每个键值是一个元组
遍历
for key in info.keys():
print(key)
#遍历所有的键值对
for key,value in info.items():
print("key=%s,value=%s"%(key,value))
#使用枚举函数同时拿到下标和内容
mylist = ["a","b","c","d"]
print(enumerate(mylist))
for i ,x in enumerate(mylist):
print(i,x)
函数
函数定义方式
def printinfo():
print("人生苦短,我用Python")
带参数的函数
def addTwoNum(a,b):
c = a+b
return c
print(addTwoNum(1,2))
返回多个参数
def divid(a,b):
shang = a/b
yushu = a%b
return shang,yushu
sh,yu = divid(5,2) #接收
文件操作
f = open("test.txt","w") #写模式 常用:r w rb wb
f.write("hello") #写入到文件
f.close() #关闭文件
f = open("test.txt","r")
content = f.read(3) #读3个字符
content = f.readlines() #读多行,以列表的形式存储
print(content)
异常
try: #捕获异常
print("first")
f = open("tes.txt")
print("second")
except Exception as result:
print(result)
finally:
print("over")