1、编写一个代码,能捕获算数异
try:
a=2
b="f"
print(a+b)
except:
print("有异常")
finally:
print("此程序无异常")
2、用户输入数据,如果是数字就%1024,如果是字符串,就输出字符串
try:
a=input("输入数据:")
if str.isdigit(a):
a=int(a)
print(a%1024)
elif str.isalpha(a):
print(a)
else:
pass
except:
print("有异常")
finally:
print("此程序没有异常")
3、编写一个程序,可以捕获多个异常
try:
# a=int(input("输入:"))
# b="f"
# print(a+b)
c=[1,3,5]
for i in range(len(c)+1):
print(c[i])
except ValueError:
print("值有异常")
except IndexError:
print("下标异常")
except:
print("发生其他异常")
finally:
print("此程序无异常")
4、读取一个文件,打印在控制台
a = open(r"C:\Users\ASUS\Desktop\output\练习.txt", encoding="utf-8")
b=a.read()
print(b)
a.close()
a = open(r"C:\Users\ASUS\Desktop\output\练习.txt", encoding="utf-8")
try:
b=a.read()
print(b)
except:
print("读取异常")
finally:
a.close()
5、读取一个文件,读取50个字符
a = open(r"C:\Users\ASUS\Desktop\output\练习.txt", encoding="utf-8")
b=a.read(50)
print(b)
a.close()
6、读取一个文件,并写入用户输入的数据
a = open(r"C:\Users\ASUS\Desktop\output\练习.txt",mode="w", encoding="utf-8")
b=input("输入:")
a.write(b)
a.close()
7、编写一段代码,实现复制一个文本文件
a = open(r"C:\Users\ASUS\Desktop\output\练习.txt", encoding="utf-8")
b=a.read(50)
c = open(r"C:\Users\ASUS\Desktop\output\jj.txt",mode="w", encoding="utf-8")
c.write(b)
c.close()
a.close()
8、编写一段代码,实现复制一个图片文件
a = open(r"C:\Users\ASUS\Desktop\lu.png","rb")
b=a.read()
c = open(r"C:\Users\ASUS\Desktop\output\new_lu.png","wb")
c.write(b)
c.close()
a.close()
9、编写一个程序,可以记录用户输入的数据,和输出的数据,下一次运行的时候,能复现这些数据
g=open(r"C:\Users\ASUS\Desktop\output\j.txt")
k=g.read()
k=int(k)
if k==1:
b = input("输入:")
c = 3 * b
a = open(r"C:\Users\ASUS\Desktop\output\jj.txt", "w")
a.write(b)
a.close()
a = open(r"C:\Users\ASUS\Desktop\output\jj.txt", "a")
a.write(" ")
a.write(c)
a.close()
e = open(r"C:\Users\ASUS\Desktop\output\jj.txt")
d = e.read()
print(d)
e.close()
k=k+1
k=str(k)
g=open(r"C:\Users\ASUS\Desktop\output\j.txt","w")
g.write(k)
g.close()
else:
e = open(r"C:\Users\ASUS\Desktop\output\jj.txt")
d = e.read()
print(d)
e.close()
10、编写一个登录模块,用户名密码是放在文件中的。
import re
a=open(r"C:\Users\ASUS\Desktop\output\j.txt",encoding="utf-8")
b=a.read()
print(b)
name1=re.findall("用户名:(\w{0,100})",b)
password1=re.findall("密码:(\w{0,100})",b)
print(name1)
print(password1)
a.close()
print("*" * 20)
name = input("用户名:")
password = input("密码:")
print("*" * 20)
print("输入正确")