二 Python题目练习( 二 )


7.凯撒密码
import random#生成10位随机字符串def createStr():STR = [chr(i) for i in range(65,91)] #对应字符A-Zsa = ''for i in range (10):sa+=random.choice(STR)print(sa)return sa#对字符串进行加密def enCaesar(sa):sa_enCaesar = ''for i in sa:if ord(i) < 91 - k:sa_enCaesar += chr(ord(i) + k)else:sa_enCaesar += chr(ord(i) + k -26)return sa_enCaesar#写入txtdef writeFile(sa_enCaesar):with open('加密.txt','w',encoding='utf-8') as f:f.write(sa_enCaesar)#读取txtdef readFile():with open('加密.txt','r',encoding='utf-8') as e:sa = e.readline()return sa#解密def deCaesar(sa):sa_deCaesar = ''for i in sa:if ord(i) >= 65+k:sa_deCaesar += chr(ord(i) - k)else:sa_deCaesar += chr(ord(i) + 26 -k)return sa_deCaesarsa = createStr()k = int(input('请输入位移值:'))sa_enCaesar = enCaesar(sa)print('加密后:')print(sa_enCaesar)writeFile(sa_enCaesar)sa = readFile()sa_deCaesar = deCaesar(sa)print('解密后:')print(sa_deCaesar)