知识点1
使用第三方库时候就没有用本地库了,所以即使在自己电脑上下载了库函数,仍然没有办法访问,但是可以添加一下本地库
文件读写操作(O/I)
#读操作
file = open("文件名",'操作')
data = file.readlines()#读入整篇文章
da = file.readline()#读入整行
#写操作
file = open("文件名",'w')
file.write('\naaa')#加入换行和字符串aaa
list = ['123','23']
file.writelines(list)#添加列表,但是只能添加字符串类型的
file.seek(2)#在两个字节之后进行查找操作
print(file.tell())#指针位置,从0开始
file.close()#关闭文件
import os
#rename重命名
os.rename('文件名','改的名字')
#remove删除
os.remove('文件名')
#with语句
with open('文件','操作') as file:
print(file.read())
#这个可以自动关闭,不需要写file.close()
知识点2
如何处理异常,可以使用try...except...except处理异常
这里可以一次写多个except来抓住不同的错误类型
最后可以写一个else,表示没有上述异常
最后还可以写finally表示程序结束
try:
pass(运行的代码)
except xxxx:(抓住的错误类型)
pass(如果抓住输出语句)
else:
pass
finally:
pass#会继续往下执行,相当于即使这段代码报错但是仍然会继续往下执行
!
raise使用方法
手动抛出一个异常,提醒程序出现了什么异常情况
try:
sort=input("请输入你的信息")
if sort!='xuesheng' and sort !='laoshi':
raise Exception("only laoshi and xuesheng")
else:
print("nideshenfen")
except Exception as x:
print(x)
怎么样才能构成一个三角形
try:
a = int(input("第一条:"))
b = int(input("第二条:"))
c = int(input("第三条:"))
if c>=a+b or b>=a+c or a>=b+c:
raise Exception("不能构成三角形")#手动创建一个异常
else:
print(a,b,c)
except Exception as x:
print(x)
判断是不是数字
a = input()
if a.isdigit():#判断是不是数字
print("是数字")
else:
print("不是数字")
会员登录
print("欢迎会员登录")
dict1 = dict();
dict1={"nihao":123}
zhanghao = input("请输入账号:")
password = input("请输入密码:")
if zhanghao not in dict1:
print("是否注册Yes/No")
f = input()
if f =='Yes':
dict1[zhanghao]=password
print("注册成功")
money = int(input("请输入购物金额:"))
if money > 1000:
money = money*0.75
elif 500 < money <= 1000:
money = money * 0.85
else:
money = money *0.95
print(f"您最后的消费金额是{money}")
else:
money = int(input("请输入购物金额:"))
print(f"您最后的消费金额是{money}")
else:
f = 1
if dict1[zhanghao]==password:
print("登陆成功")
money = int(input("请输入购物金额:"))
if money > 1000:
money = money*0.75
elif 500 < money < 1000:
money = money * 0.85
else:
money = money *0.95
print(f"您最后的消费金额是{money}")
else:
print("密码错误")
while f<3:
password = int(input("请再次输入:"))
if dict1[zhanghao] == password:
break
if f<3:
money = int(input("请输入购物金额:"))
if money > 1000:
money = money * 0.75
elif 500 < money < 1000:
money = money * 0.85
else:
money = money * 0.95
print(f"您最后的消费金额是{money}")
else:
print("账号被锁")
money = int(input("请输入购物金额:"))
print(f"您最后的消费金额是{money}")