一、计算文件大小
import osdef get_size(path): size = 0 l = [path] while l: path = l.pop() lst = os.listdir(path) for name in lst: son_path = os.path.join(path,name) if os.path.isfile(son_path): size += os.path.getsize(son_path) else: l.append(son_path) return sizesize = get_size(r'D:\s14\算法')print(size)
二、三级菜单
l = [menu]while l: for k in l[-1]: print(k) key = input('>>>') if key.upper() == 'B': l.pop() elif key.upper() == 'Q': l.clear() elif l[-1].get(key): l.append(l[-1][key])
三、文件监听
def func(): with open('test.txt', 'r+', encoding='utf-8') as f: while 1: lens = f.readline() if lens: yield lenst = func()for j in t: print(j)
四、发红包
import randomdef rea_pac(money,num): ret = random.sample(range(1,money*100),num-1) print(ret) ret.sort() ret.insert(0,0) ret.append(money*100) for i in range(len(ret)-1): value = ret[i+1] - ret[i] yield value/100g = rea_pac(200,10)for i in g: print(i)
五、递归问路
lis = ['alex','wusir','yuanhao','linhaifeng','henry']def inner(name): if len(name) == 0: return '没有找到路' res = lis.pop(0) if res == 'henry': return '%s说:我知道老男孩就在沙河地铁站附近'%res print('hi美男%s敢问路在何方'%res) print('%s回答道,我也不知道,我帮你问问%s'%(res,lis)) f = inner(lis) return fprint(inner(lis))
找到路后会把结果返回给上一个调用者’linhaifeng’
‘linhaifeng’会把结果返回给上一个调用者’yuanhao’…
最终会把结果返回给最开始的调用者inner
六、人狗大战
import randomimport time
定义一个人的类
class Person: # 定义人的静态属性 def __init__(self,name,hp,ad,sex): self.name = name self.ad = ad self.hp = hp self.sex = sex # 定义人的方法 def da(self,dog): yy = random.randint(1,self.ad) dog.hp -= yy print('%s使用%s,打了%s,%s掉了%s点血'%(self.name,arms.name,dog.name,dog.name,yy)) if dog.hp < 50: print("{}使用终极必杀技{}".format(dog.name,arms.skill()))
定义一个狗的类
class Dog: # 定义狗的静态属性 def __init__(self,name,hp,ad,kind): self.name = name self.hp = hp self.ad = ad self.kind = kind # 定义狗的方法 def yao(self,person): uu = random.randint(1,self.ad) person.hp -= uu print('%s咬了%s,%s掉了%s点血' % (self.name, person.name, person.name,uu)) if person.hp < 50: print("{}使用终极必杀技{}".format(person.name,arms.skill()))
定义一个武器类
class Arms: def __init__(self,name,hp,ad): self.name = name self.hp = hp self.ad = ad # 定义一个武器的技能 def skill(self): li = ['飞龙在天','乾坤大挪移','九阳神功'] f = random.choice(li) return farms = Arms('铁锹',3000,2000)henry = Person('henry',500,30,'男')dog = Dog('大黄',300,30,'哈士奇')c = 1while dog.hp > 0: print('第{}回合'.format(c)) dog.yao(henry) henry.da(dog) time.sleep(1) c +=1
七、计算器
import reexpress = '1-2*((60-30+(9-2*5/3+7/3*99/4*2998+10*568/14)*(-40/5))-(-4*3)/(16-3*2))'express = express.replace(' ','')
计算
def cout(exp): if '*' in exp: a,b = exp.split('*') return str(float(a) * float(b)) else: a, b = exp.split('/') return str(float(a) / float(b))
表达式的符号管理把++变成+,–变成-,±变成-,-+变成-
def format_exp(exp): exp = exp.replace('++','+') exp = exp.replace('+-','-') exp = exp.replace('--','+') exp = exp.replace('-+','-') return exp
计算所有的乘除法
def cal_no(res): while True: chengshu = re.search('\d+\.?\d*[*/]-?\d+\.?\d*', res) # (9-2*5/3+7/3*99/4*2998+10*568/14) if chengshu: ret = chengshu.group() # 2*5 resut = cout(ret) # 得到乘除法的计算结果 10.0 # 将2*5替换成10.0 res = res.replace(ret, resut) # (9-10.0/3+7/3*99/4*2998+10*568/14) else:break print(res) # (9-3.3333333333333335+173134.50000000003+405.7142857142857) # 表达式的符号管理把++变成+,--变成-,+-变成-,-+变成- res1 = format_exp(res) # 将替换后的结果从新赋值给res # 将括号内的加减法都匹配出来 res_lis = re.findall('[-+]?\d+(?:\.\d+)?',res1) print(res_lis) # ['9', '-3.3333333333333335', '+173134.50000000003', '+405.7142857142857'] sum_n = 0 for i in res_lis: sum_n += float(i) return sum_ndef remove_bracket(express): while True:
提取表达式最里层的括号
exp = re.search('\([^()]+\)',express) if exp: res = exp.group() # (9-2*5/3+7/3*99/4*2998+10*568/14) rep = cal_no(res) # 173545.88095238098 print(rep) express = express.replace(res,str(rep)) # 因为rep的结果是一个数字 print(express) # 1-2*((60-30+173545.88095238098*(-40/5))-(-4*3)/(16-3*2)) else:break return express # 括号内的表达式全部计算完成1-2*-1388338.2476190478ret = remove_bracket(express)print(cal_no(re
八、校验文件的一致性
# import os# import hashlib# def file_md5(path):# filesize = os.path.getsize(path)# md5 = hashlib.md5()# with open(path,'rb') as f:# while filesize >= 4096:# content = f.read(4096)# md5.update(content)# filesize -= 4096# else:# content = f.read(filesize)# if content:# md5.update(content)# return md5.hexdigest()## def cmp_file(path1,path2):# return file_md5(path1) == file_md5(path2)# path1 = r'D:\s20\day18\视频\4.面向对象整理.mp4'# path2 = r'D:\s20\day18\视频\tmp.mp4'# ret = cmp_file(path1,path2)# print(ret)
九、打印九九乘法表
for i in range(1,10): for j in range(1,i+1): print("%s*%s=%s"%(i,j,i*j),end=' ') print()for i in range(1,10): for j in range(i,10): print("%s*%s=%s"%(i,j,i*j),end=' ') print()
十、购物车作业
创建一个名为‘购买账单的txt文件
goods = []money = input('请充值充值金额').strip()with open('商品信息',encoding='utf-8')as f: for i in f: xinxi = i.strip().split(' ') if xinxi[0] == 'name': continue else: dic = dict([('name',xinxi[0]),('price',xinxi[1])]) goods.append(dic)print(goods)"""页面显示 序号 + 商品名称 + 商品价格"""a = 1for v in goods: print(a,v['name'],v['price']) a += 1print('n 购物车结算')print('q 或 Q 退出')shop_dic = {}sum = 0a = 1dic = {}balance = 0while 1: shuru = input('请输入序号').strip() if shuru.isdigit() and (0 < int(shuru) <= len(goods)): print(goods[int(shuru)-1]['name'],goods[int(shuru)-1]['price'])
购物车添加商品名称和价格和数量
shop_dic.setdefault(goods[int(shuru)-1]['name'],{'price':goods[int(shuru)-1]['price'],'amount':0})
增加商品数量
shop_dic[goods[int(shuru)-1]['name']]['amount'] += 1 elif shuru == 'n': for k,j in shop_dic.items(): # python学习交流群:309488165 # 展示购物车商品名称价格数量 print(a,k,j['price'],j['amount'])
带序号和商品名称的字典
dic[a] = k a += 1 sum += int(j['price'])*int(j['amount']) if int(money) >= sum: print('结算成功') balance = int(money)-sum for s, b in shop_dic.items(): print(s, b['price'], b['amount']) print('共计消费{}元,剩余金额{}元'.format(sum, balance)) break while int(money) < sum: print('余额不足') shanchu = input('请输入要删除的商品序号')
用户选择删除购物车里的商品则在购物车里将数量减一
shop_dic[dic[int(shanchu)]]['amount'] -= 1 sum = sum - int(shop_dic[dic[int(shanchu)]]['price']) else: print('结算成功') balance = int(money) - sum for s, b in shop_dic.items(): print(s, b['price'], b['amount']) print('共计消费{}元,剩余金额{}元'.format(sum, balance)) break elif shuru.upper() == 'Q': print('程序退出') break else: print('输入有误请重新输入')with open('购买账单',encoding='utf-8',mode='w') as f1: for s, b in shop_dic.items(): f1.write('商品名称:{} '.format(s)) f1.write('单价:{} '.format(b['price'])) f1.write('数量:{}\n'.format(str(b['amount']))) f1.write('共计消费{}元\n'.format(sum)) f1.write('剩余金额%s元'%(balance))
十一、博客园登录
创建一个log和register文件
import timedic = { 1: '请登录', 2: '请注册', 3: '文章页面', 4: '日记页面', 5: '评论页面', 6: '收藏页面', 7: '退出程序',}def Home_display(): """
首页展示
:return: """ print('欢迎来到博客园首页!!!') for i in dic: print(i,dic[i])Home_display()def ster(): """
用户注册函数,将用户名,密码写入文件
:return: """ user_name = input('请填写注册名称').strip() pass_word = input('请填写注册密码').strip() with open('register','a+',encoding='utf-8') as f1: f1.write('{},{}'.format(user_name,pass_word)+'\n') print('注册成功,请登录!!!')def login_system(): """
登录函数
:return: """ user_name = [] time = 3 with open('register', 'r+', encoding='utf-8') as f: for i in f: user_name.append(i.strip()) while time >= 1: name = input('请输入用户名') wd = input('请输入密码') l = name + ',' + wd if l in user_name: print('登录成功') chioce(name) else: time -= 1 if time == 0: print('登录次数超出限制,请您注册后登录!') break print('用户名或密码错误,剩余{}次机会'.format(time))def eixt_procedure(): """
退出程序
:return: """ print('程序退出,欢迎下次光临') exit()def log(n,func): with open('log','a+',encoding='utf-8') as f2: current_time = time.strftime("%Y-%m-%d-%X",time.localtime()) f2.write('{}:{}调用了{}函数'.format(n,current_time,func) + '\n')def diary(n): """
日记页面
:return: """ print('欢迎{}访问日记页面'.format(n)) log(n, 'diary')def comment(n): """
评论页面
:return: """ print('欢迎{}访问评论页面'.format(n)) log(n, 'comment')def Collection(n): """
收藏页面
:return: """ print('欢迎{}访问收藏页面'.format(n)) log(n, 'Collection')def Article(n): """
文章页面
:return: """ print('欢迎{}访问文章页面'.format(n)) log(n, 'Article')lis = [login_system,ster,Article,diary,comment,Collection,eixt_procedure,log]def chioce(a): """
用户选择函数
:return: """ while 1: number = input('请选择页面:').strip() if number.isdigit() and 3 <= int(number) <= 6: lis[int(number)-1](a) # 不可以输入字母 elif number.isdigit() and (int(number) ==1 or int(number)==7): if int(number)==7: eixt_procedure() lis[int(number) - 1]() else: print('请输入正确页面选项:')def chioce1(): while 1: number = input('请选择登录或注册或退出').strip() if number.isdigit() and (1 == int(number) or int(number) == 7 or int(number) == 2) : if int(number) == 7: eixt_procedure() else: lis[int(number)-1]() else: print('输入有误请重新输入')chioce1()
十二、学生选课系统
创建course_file,test.log,vip_admin 文件
import hashlibimport pickleimport osimport logginglogger = logging.getLogger()
创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',encoding='utf-8')
再创建一个handler,用于输出到控制台
# ch = logging.StreamHandler()formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh.setFormatter(formatter)# ch.setFormatter(formatter)logger.addHandler(fh) #logger对象可以添加多个fh和ch对象# logger.addHandler(ch)logger.setLevel(logging.DEBUG)# python学习交流群:309488165# 密码加密def md5_user(username,password): md5 = hashlib.md5(username.encode('utf-8')) md5.update(password.encode('utf-8')) return md5.hexdigest()
读取文件
def read_file_name(file_name): with open(file_name,'rb') as f: while True: try: res = pickle.load(f) if res: yield res except EOFError: break
写文件
def add_file(file_name,content): with open(file_name,'ab') as f: pickle.dump(content,f)
创建课程类
class Course: def __init__(self,name,price,period,teacher): self.name = name self.price = price self.period = period self.teacher = teacher def __str__(self): return format('\t课程:' + self.name,'<13') + format('价钱:' + self.price,'<13') + format('周期:' + self.period,'<13') + format('老师:' + self.teacher,'<13')class Admin: msg = [('创建课程', 'course'), ('创建学生和学生账号', 'account_num'), ('查看所有课程', 'view_courses'), ('查看所有学生', 'look_all_student'), ('查看所有学生的选课情况', 'look_all_courses'), ('退出程序', 'quit')]
实例化出一个管理员
def __init__(self,username,password,identify='Admin'): self.username = username self.password = password self.identify = identify
创建课程
def course(self): student_name = input('请输入课程名称') student_pricce = input('请输入课程价钱') student_period = input('请输入课程周期') student_teacher = input('请输入授课老师') Course1 = Course(student_name,student_pricce,student_period,student_teacher) add_file('course_file', Course1) return True
创建学生和学生账号
def account_num(self): username = input('请输入要创建的姓名') password = input('请输入要创建的密码') student1 = Student(username,md5_user(username,password)) add_file('vip_admin', student1) return True
查看所有课程
def view_courses(self): ret = read_file_name('course_file') for index,i in enumerate(ret,1): print(index,i) # 因为用__str__所以直接打印对象名直接可以打印他的return值 return True
查看所有学生
def look_all_student(self): ret = read_file_name('vip_admin') for i in ret: if i.identify == 'Student': print(i.username,i.password) return True
查看所有学生的选课情况
def look_all_courses(self): ret = read_file_name('vip_admin') for i in ret: if i.identify == 'Student': print(i.username) for j in i.course: print(j) return True
退出程序
def quit(self): print('程序退出') logger.info(self.username + '——' + self.msg[-1][0]) exit()
实例化一个alex密码123的管理员
# alex = Admin('alex',md5_user('alex','123'))# def write_file_name():# with open('vip_admin','wb') as f:# pickle.dump(alex,f)# write_file_name()class Student: msg = [('查看所有课程', 'look_all_course'), ('选择课程', 'choice_course'), ('查看所选课程', 'look_choice_course'), ('退出程序', 'quit')] def __init__(self,username,password,identify = 'Student'): self.username = username self.password = password self.identify = identify self.course = [] def look_all_course(self): ret = read_file_name('course_file') for index, i in enumerate(ret, 1): print(index, i) return True def choice_course(self): ret = list(read_file_name('course_file')) # print(ret) for index, i in enumerate(ret, 1): print(index, i) while True: choice = input('请选择课程>>>:').strip() if choice.isdigit() and int(choice) in range(1,len(ret) +1 ): print(ret[int(choice)-1].name) print([i.name for i in self.course]) if ret[int(choice)-1].name not in [i.name for i in self.course]: self.course.append(ret[int(choice)-1]) with open('vip_admin','rb') as f1,open('vip_admin2','wb') as f2: while True:try: res1 = pickle.load(f1) if res1.username == self.username: res1.course.append(ret[int(choice)-1]) pickle.dump(res1,f2) else: pickle.dump(res1, f2)except EOFError:break os.remove('vip_admin') os.rename('vip_admin2','vip_admin') logger.info(self.username + '——' + self.msg[1][0]+ str(ret[int(choice)-1])) # ????? break else: print('该课程您已选择') break else: print('输入有误重新输入') def look_choice_course(self): ret = read_file_name('vip_admin') for i in ret: if i.username == self.username: for j in i.course: print(j) return True def quit(self): logger.info(self.username + '——' + self.msg[-1][0]) exit()
登录验证
def login(username,password): ret = read_file_name('vip_admin') for i in ret: # print(i.username) if i.username == username and i.password == md5_user(username,password): return i else:return Falsedef auth(): lis = ['登录','退出'] while True: for index,opt in enumerate(lis,1): print(index,opt) num = input('请输入你要操作的内容') if num.isdigit() and int(num) in range(1,len(lis)+1): if num == '1': username = input('请输入用户名') password = input('请输入密码') ret = login(username,password) if ret: print('登录成功') logger.info(username + '——' + '登录成功') return ret else: print('登录失败') elif num == '2': exit() else: print('您输入的序号有误请重新输入')
主函数
def main(): ret = auth() # if hasattr(sys.modules[__name__],ret['identify']): # cls = getattr(sys.modules[__name__],ret['identify']) # ??????? # # print(sys.modules[__name__]) # <module '__main__' from 'D:/PycharmProjects/s20/大作业/Thursday/学生选课系统升级版/选课系统升级版.py'> # obj = cls(ret['username'],ret['password']) if ret: # print(ret) obj = ret # print(obj) while True: for index,i in enumerate(obj.msg,1): print(index,i[0]) choice = input('请选择序号') if choice.isdigit() and int(choice) in range(1,len(obj.msg) + 1): if hasattr(obj,obj.msg[int(choice) - 1][1]): if callable(getattr(obj,obj.msg[int(choice) - 1][1])): ret = getattr(obj, obj.msg[int(choice) - 1][1])() if ret:logger.info(obj.username+'——'+obj.msg[int(choice) - 1][0]) else: print('您输入的序号有误,请重新输入')main()
最后
文章提供的十二道编程题,大家都可以自己研究研究,有不理解的地方也是可以点击文章末尾名片 进行交流学习的哦
刚开始学习python的朋友,或者对python感兴趣还没开始学习的宝子,也可以点击名片领取大量的学习资料以及部分案例的源码哦
希望我们可以一起学习,一起进步~