从零开始学Python06作业源码(仅供参考)

时间:2023-12-28 12:25:26

Python Version 2.7x

一,bin目录:程序启动入口

  •   SelectLesson_start.py
 #!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述: import sys
sys.path.append('..')
from src import users_business users_business.user_Main()

二,lib目录:公共模型目录

  • Teachers_model.py
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述:教师模型类 class teacher_Model:
'''
教师模型类
'''
def __init__(self,name,age,sex):
self.Name = name #姓名
self.Age = age #年龄
self.Sex = sex #性别
self.__Calary = 0 #工资 def teacher_Accident(self): #教学事故
self.__Calary -= 10 def teacher_Success(self,cost): #教学成功
self.__Calary += int(cost) def calary_Return(self): #返回工资数据
return self.__Calary
  • Lessons_model.py
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述: import random,time class lesson_Model:
'''
课程模型类
'''
def __init__(self,lname,lcost,tobj):
self.Lname = lname #课程名
self.Lcost = lcost #课时费
self.Tobj = tobj #授课老师
self.difficulty = random.randrange(10,40) #授课难度 def classBegins(self): #上课方法
if self.success_Radio():
self.Tobj.teacher_Success(self.Lcost)
return True
else:
self.Tobj.teacher_Accident()
return False def success_Radio(self): #授课随机意外率
num = random.randrange(1, 1000)
if num <= (100-self.difficulty) * 10:
return True
else:
a = random.randrange(1, 5)
# print (type(a))
lesson_Model.event(str(a))
return False @staticmethod
def event(num): #授课意外事件
dict = {'': '据说老师刚刚失恋了,授课状态很差', '': '据说老师已经递交了辞职报告,授课状态很差',
'': '据说老师相亲去了,到现在状态都还没恢复。', '': '据说老师家里节哀了,心情极度悲伤',
'': '据说老师钱包丢了,内心无比哀叹'}
time.sleep(1)
print(dict[num])
  • Students_model.py
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述:
import random,time class student_Model:
'''
学生模型类
''' # num = 0
def __init__(self,name,age,account,password,lobj):
self.Name = name #姓名
self.Age = age #年龄
self.Account = account #账户名
self.Password = password #密码
self.Lobj = lobj #课程对象列表
self.IQ= random.randrange(40,90) #随机智商
self.schedule = {}
self.num = {}
for lesson in self.Lobj:
self.schedule[lesson] = 0 #课程进度率字典
self.num[lesson] = 0 #课程修业次数 def Classbegins(self,lesson_name): #上课
for obj in self.Lobj:
if obj.Lname == lesson_name :
# print (self.num)
print('{0}课程进行第{1}次修业...'.format(obj.Lname, str(self.num[obj] + 1)))
time.sleep(1)
if self.success_Radio():
tag = obj.classBegins()
if tag:
self.schedule[obj] += 20
self.num[obj] += 1
time.sleep(1)
print ('你感觉非常好!')
time.sleep(1)
print ('{0}:{1}课程学习成功!完成率提高20%,达成率变为{2}%'.format(self.Name,obj.Lname,str(self.schedule[obj])))
else:
self.num[obj] += 1
time.sleep(1)
print ('你突然有一种骂娘的冲动...')
time.sleep(1)
print ('{0}:{1}课程学习失败,你对课程的理解没有丝毫提高,达成率为{2}%'.format(self.Name,obj.Lname,str(self.schedule[obj])))
else:
tag = obj.classBegins()
if tag:
self.schedule[obj] += 10
self.num[obj] += 1
time.sleep(1)
print('{0}:{1}课程学习欠佳!完成率提高10%,达成率变为{2}%'.format(self.Name,obj.Lname, str(self.schedule[obj])))
else:
self.num[obj] += 1
time.sleep(1)
print('你突然萌生了轻生的念头...')
time.sleep(1)
print('{0}:{1}课程学习失败,你对课程的理解没有丝毫提高,达成率为{2}%'.format(self.Name, obj.Lname,
str(self.schedule[obj])))
else:
pass def success_Radio(self): #学习随机意外率
num = random.randrange(1, 1000)
if num <= self.IQ * 10:
return True
else:
a = random.randrange(1,5)
# print (type(a))
student_Model.event(str(a))
return False @staticmethod
def event(num): #学习意外事件
dict = {'':'你感觉头晕脑胀,浑身乏力!','':'外面突然飞过一只蜻蜓,你看着他飞了一节课!',
'':'女朋友来短信了,你激动的忘了听课','':'你突然感觉肚子疼...原来是想拉屎了',
'':'你的眼镜片碎了....'}
time.sleep(1)
print (dict[num])
  •  common.py
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述: #!/usr/bin/python
# -*- coding: utf-8 -*-
# 公共方法层 import os,time,random,pickle DIR = os.path.dirname(__file__)
DIR = DIR.replace('lib','db/') TAG = True #循环控制标志 def Exit():
'''
系统退出
:return:None
'''
print ('程序退出!')
exit() def MD5(password):
'''
加密函数
:param firstsite: 密码字符串
:return: 加密字符串
'''
import hashlib
return hashlib.md5(password).hexdigest() def Verification_input():
'''
登录验证码校验
:return: True
'''
while TAG:
re = Verification_Code()
code = raw_input('请输入括号里的验证码,不区分大小写({0}):'.format(re))
if code.strip().lower() != re.lower():
print('您输入的验证码有误,请重新输入!')
else:
return True def Verification_Code():
'''
生成随机的6位验证码:大小写字母数字的组合
:return: 验证码
'''
code = ''
b = random.randrange(0, 5)
c = random.randrange(0, 5)
for i in range(6):
if i == b:
a = random.randrange(1, 9)
code = code + str(a)
else:
a = random.randrange(65, 90)
if i == c:
code = code + chr(a).lower()
else:
code = code + chr(a)
return code def log_info_read(dir):
'''
配置文件全部读取
:param user:用户名
:return:dict字典
如果无文件返回False
'''
if os.path.exists(dir):
with open(dir,'r') as f:
dict = pickle.load(f)
return dict
else:
return False def log_info_write(dir,dict):
'''
配置文件全部写入
:param user:用户名
:param dict: 日志字典
:return: True or False
'''
#if os.path.exists(user+'_log'):
#print (DIR+user+'_log')
with open(dir,'w') as f:
pickle.dump(dict,f)
return True

三,src目录:程序业务目录

  • admin_business.py
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述: import os,sys
sys.path.append('..')
from lib.Teachers_model import teacher_Model
from lib.Lessons_model import lesson_Model
from lib import common DIR = os.path.dirname(__file__)
DIR = DIR.replace('src','db/') TAG = True def create_Teachers_model():
"""
创建老师模型
:return: None
"""
while TAG:
name = raw_input("请输入老师的姓名:")
age = raw_input("请输入老师的年龄:")
sex = raw_input("请输入老师的性别:")
while TAG:
text = """
老师信息如下:
姓名:{0}
年龄:{1}
性别:{2}
""".format(name,age,sex)
print (text)
decide = raw_input("是否确认(y/n):")
if decide == 'y':
P = teacher_Model(name,age,sex)
dict = common.log_info_read(DIR+'config_conf')
if dict != False:
dict['teachers'].append(P)
common.log_info_write(DIR + 'config_conf', dict)
print ("老师信息保存成功!")
return
else:
dict = {
'teachers':[P],
'lessons':[],
'students':[]
}
common.log_info_write(DIR+'config_conf',dict)
print ("老师信息保存成功!")
return
elif decide == 'n':
break
else:
print ("您的输入有误!") def create_Lesson_model():
"""
创建课程模型
:return: None
"""
num = 0
list = []
dict = common.log_info_read(DIR + 'config_conf')
if dict == False:
print ("请先创建老师模型后再来!")
return
name = raw_input("请输入课程名称:")
cost = raw_input("请输入课时费:")
while TAG:
print ("目前有{0}个老师可供选择,如下:".format(str(len(dict['teachers']))))
for P in dict['teachers']:
print ("{0}:姓名:{1},年龄:{2},性别:{3}".format(str(num+1),P.Name,P.Age,P.Sex))
num += 1
list.append(str(num))
choose = raw_input("请输入索引选择授课老师:")
if choose in list:
tobj = dict['teachers'][int(choose)-1]
L = lesson_Model(name,cost,tobj)
while TAG:
text = """
课程的信息如下:
课程名:{0}
课时费:{1}
授课老师:{2}
""".format(name, cost, L.Tobj.Name)
print (text)
decide = raw_input("是否确认(y/n):")
if decide == 'y':
dict['lessons'].append(L)
common.log_info_write(DIR + 'config_conf', dict)
return
elif decide == 'n':
return
else:
print ("您的输入有误!")
else:
print ("您的输入有误!")
num = 0 def model_Config():
"""
查看已经创建的模型
:return: None
"""
num = 0
Num = 0
dict = common.log_info_read(DIR + 'config_conf')
if dict == False:
print ("请先创建老师模型后再来!")
return
print ("已经创建的老师模型,如下:".format(str(len(dict['teachers']))))
for P in dict['teachers']:
print ("{0}:姓名:{1},年龄:{2},性别:{3}".format(str(num + 1), P.Name, P.Age, P.Sex))
num += 1
print ("已经创建的课程模型,如下:".format(str(len(dict['teachers']))))
for P in dict['lessons']:
print ("{0}:课程名:{1},课时费:{2},授课老师:{3}".format(str(Num + 1), P.Lname, P.Lcost, P.Tobj.Name))
Num += 1 def admin_Main(log = None):
"""
管理员管理界面
:param log: 用户登录标志
:return: None
"""
while TAG:
text = """
欢迎来到管理员界面 {0}登陆中
1,创建老师模组
2,创建课程模组
3,查看模组配置
4,系统退出
""".format(log)
print (text)
while TAG:
choose = raw_input('请输入你的选择:')
if choose == '':
create_Teachers_model()
break
elif choose == '':
create_Lesson_model()
break
elif choose == '':
model_Config()
break
elif choose == '':
common.Exit()
else:
print ('您的输入有误!') if __name__ == "__main__":
admin_Main('admin')
  • users_business.py
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述: LOGIN = []
TAG = True
import os,sys
sys.path.append('..')
from lib import common
from lib.Students_model import student_Model
from src import admin_business DIR = os.path.dirname(__file__)
DIR = DIR.replace('src','db/') def user_Login():
dict = common.log_info_read(DIR + 'config_conf')
if dict == False:
print ("请让管理员先创建老师及课程模型后再来!")
return
while TAG:
account = raw_input("请输入你的登录名:")
if account == 'admin':
password = raw_input("请输入你的登陆密码:")
if password == '':
admin_business.admin_Main('admin')
for S in dict['students']:
if S.Account == account:
while TAG:
password = raw_input("请输入你的登陆密码:")
if S.Password == password:
print ('登陆成功')
LOGIN.insert(0,S)
user_Main(S.Name)
else:
print ("您输入的密码有误!")
else:
print ("您输入的账号有误,请重新输入!") def login_Check():
dict = common.log_info_read(DIR + 'config_conf')
if dict == False:
print ("请让管理员先创建老师及课程模型后再来!")
return
name = raw_input("请输入你的姓名:")
age = raw_input("请输入你的年龄:")
account = raw_input("请输入你的登录账号:")
password = raw_input("请输入你的登陆密码:")
text = """
你的注册信息如下:
姓名:{0}
年龄:{1}
登陆账号:{2}
登陆密码:{3}
""".format(name,age,account,password)
while TAG:
print (text)
decide = raw_input("是否确认(y/n):")
if decide == 'y':
S = student_Model(name,age,account,password,[])
dict['students'].append(S)
common.log_info_write(DIR + 'config_conf', dict)
LOGIN.insert(0,S)
print ('信息注册成功')
user_Main(name)
elif decide == 'n':
return
else:
print ('你的输入有误!') def select_Lesson():
num = 0
List = []
dict = common.log_info_read(DIR + 'config_conf')
if LOGIN == []:
print ('请登陆后再来!')
return
if dict == False:
print ("请让管理员先创建老师及课程模型后再来!")
return
print ("目前的可选课程有{0}门,如下:".format(str(len(dict['lessons']))))
for lesson in dict['lessons']:
print ('{0},课程名:{1},课时费:{2},授课老师:{3}'.format(str(num+1),lesson.Lname,lesson.Lcost,lesson.Tobj.Name))
num += 1
List.append(str(num))
while TAG:
choose = raw_input("请输入索引选择课程(可以多选但不能重复):")
if choose.isdigit():
if len(choose) == len(set(choose)):
if set(choose) & set(List) == set(choose):
for S in dict['students']:
if S.Name == LOGIN[0].Name:
for i in list(choose):
if dict['lessons'][int(i)-1] in S.Lobj:
print ("您已经添加过{0}课程了".format(dict['lessons'][int(i)-1].Lname))
else:
S.Lobj.append(dict['lessons'][int(i)-1])
S.schedule[dict['lessons'][int(i)-1]] = 0
S.num[dict['lessons'][int(i) - 1]] = 0
common.log_info_write(DIR + 'config_conf', dict)
print ('选课成功!')
return
else:
pass
else:
print ("您的选择超范围,请重新选择!")
else:
print ("您的选择里有重复内容,请重新输入!")
else:
print ('您的输入必须是纯数字,请重新输入!') def class_Begins():
num = 0
List = []
dict = common.log_info_read(DIR + 'config_conf')
if LOGIN == []:
print ('请登陆后再来!')
return
if dict == False :
print ("请让管理员先创建老师及课程模型后再来!")
return
for S in dict['students']:
if S.Name == LOGIN[0].Name and S.Lobj == []:
print ("您还没有选课,请选课后再来!")
return
while TAG: for obj in dict['students']:
if obj.Name == LOGIN[0].Name:
print ("您有{0}门待修业课程,如下:".format(str(len(obj.Lobj))))
for lesson in obj.Lobj:
if obj.schedule[lesson] >= 100:
finished = '已达成'
elif obj.num[lesson] >= 9:
finished = '修业失败'
else:
finished = obj.schedule[lesson]
print ('{0},课程名:{1},课时费:{2},授课老师:{3},修业达成率:{4},已修业次数:{5}'.format(str(num+1),lesson.Lname,lesson.Lcost,lesson.Tobj.Name,finished,obj.num[lesson]))
num += 1
List.append(str(num))
choose = raw_input("请输入你的选择(单选)(输入n返回上一级菜单):")
if choose in List:
# if LOGIN[0].schedule[LOGIN[0].Lobj[int(choose)]] < 100:
for obj in dict['students']:
if obj.Name == LOGIN[0].Name:
for i in range(9):
# print (obj.Lobj[int(choose)-1])
if obj.schedule[obj.Lobj[int(choose)-1]] < 100 and obj.num[obj.Lobj[int(choose)-1]] < 9:
obj.Classbegins(obj.Lobj[int(choose)-1].Lname)
num = 0
else:
print ('您选择的课程已经修业完成,请重新选择!')
common.log_info_write(DIR + 'config_conf', dict)
num = 0
break
common.log_info_write(DIR + 'config_conf', dict)
elif choose == 'n':
return
else:
print ("您的输入有误!")
num = 0 def user_Main(log = None):
if log == None:
log = '用户未登录...'
else:
log = "{0}登陆中...".format(log)
text = """
欢迎光临选课系统 {0}
1,学生登录
2,学生注册
3,学生选课
4,学生上课
5,系统退出
""".format(log)
while TAG:
print (text)
dict = {'':user_Login,'':login_Check,'':select_Lesson,'':class_Begins,'':common.Exit}
choose = raw_input("请输入你的选择:")
if choose in dict.keys():
dict[choose]()
else:
print ("你的输入有误!") if __name__ == "__main__":
user_Main()

四,db目录:配置文件目录,程序自动生成