Day7 Homework: Course selection system

Source: Internet
Author: User

This week's homework is a little rough, let's see, give us some ideas:

Readme:

Need to install module:    prettytable Test Account:    1. Background management: Admin/admin   only set the background management account, not write to the database    2. The student selection system needs to be registered before the login operation, test account cc/ 123, also can register the new account use design idea:    1. Use pickle to store data, data types for teachers, students, subjects of course    2. Use process for: Create teacher--Create a course, and associate teacher-to-student registration and login-Student selection , class, etc.    3. Changes in the teacher's assets are triggered by the student's choice of class or course accident, and the administrator does not have permission to operate    4. Teacher name is unique, as the data ID ID The difficulty of this lesson:    1. The overall comparison is simple, the difficulty lies in the data association in the last database.    2. Since the same object is stored in a different database, the deserialized value is not the same, and a brief description is that the object is not a reference relationship after it is saved    3. So when you save the object, the teacher name is marked in the object property, and the course name is used as the reference ID to match the relevant data.

Flow chart:

Catalogue Description:

Directory Description: |____bin    execution directory, program portal | |____init_all_data.py     Initialization Database | |____manage.py    Admin Portal | |____student.py   Student Portal |____conf   Profile Directory | |____setting.py   configuration file |____core   Main program Directory | |____manage_sys.py    Management Main program | |____student.py       Student Master Program |____data   Database directory | |____manage.pickle    teacher Object Data | |____student.pickle   Student Object Data | |____ Subject.pickle   Course Object data

Code:

Bin/init_all_data:

#!/usr/bin/env python#-*-coding=utf-8-*-# Auther:ccorz mail:[email protected] blog:http://www.cnblogs.com/ccorz/# Github:https://github.com/ccorzorzimport Sys,os,picklebase_dir=os.path.dirname (Os.path.dirname (Os.path.abspath ( __file__))) Sys.path.append (base_dir) # Print (Base_dir) from conf.setting import *from core import Manage_sysfrom Core Import student "" "System data Initialization program, use cautiously!!!!!" "" #将所有pickle数据库中的数据写入空列表manage_sys. Data_flush ([]) Manage_sys.subject_data_flush ([]) Student.student_data_flush ([])

bin/manage.py

#!/usr/bin/env python#-*-coding=utf-8-*-# Auther:ccorz mail:[email protected] blog:http://www.cnblogs.com/ccorz/# Github:https://github.com/ccorzorzimport Sys,osbase_dir=os.path.dirname (Os.path.dirname (Os.path.abspath (__file_ _))) Sys.path.append (base_dir) Import Core.manage_sys "" "Admin background entrance, test account Admin/admin" "" If __name__ = = ' __main__ ':    Core.manage_sys.login ()    Core.manage_sys.main ()

bin/student.py

#!/usr/bin/env python#-*-coding=utf-8-*-# Auther:ccorz mail:[email protected] blog:http://www.cnblogs.com/ccorz/# Github:https://github.com/ccorzorzimport Sys,osbase_dir=os.path.dirname (Os.path.dirname (Os.path.abspath (__file_ _))) Sys.path.append (base_dir) Import core.student "" "Student system entry, can register login, or test account cc/123" "" If __name__ = = ' __main__ ':    Core.student.main ()

conf/setting.py:

#!/usr/bin/env python#-*-coding=utf-8-*-# Auther:ccorz mail:[email protected] Blog:http://www.cnblogs.com/ ccorz/# github:https://github.com/ccorzorzimport Os,sys,timebase_dir=os.path.dirname (Os.path.dirname ( Os.path.abspath (__file__)) sys.path.append (Base_dir) "" "Profile" "#存储老师信息的数据文件manage_data_file = '%s/data/ Manage.pickle '%base_dir# stores data files for course Information subject_data_file= '%s/data/subject.pickle '%base_dir# data files for storing student information student_data        _file= '%s/data/student.pickle '%base_dir# definition teacher class Teacher:def __init__ (self,name,age,favor): Self.favor=favor        Self.name=name self.age=age self.asset=0 def gain (self,value): "" "the teacher's assets increased during the class         :p Aram Value: Lesson Fee: Return: "" "Self.asset=int (Self.asset) +int (value) def teach_accidents (self): "" "Teacher asset reduction in course of accident: return:" "Self.asset-=1from Core import manage_sys# Define Course classes Class Subje   Ct:def __init__ (self,classes,value,teacher_name): #构造方法 self.classes=classes     Self.value=int (value) self.teacher_name=teacher_name def attend_class (self): "" "Class, and the corresponding teacher's        Asset Adjustment: Return: "" Print (' Come to class, today we learn%s '%self.classes) ' Print (5* ('%s ... '%self.classes))        Time.sleep (1) print (' QI-Live!!!! After class ')        Teacher_obj,index=manage_sys.sub_match_teacher (self.classes) #执行老师对象的资产增加方法 Teacher_obj.gain (Self.value)    Teacher_data=manage_sys.data_read () teacher_data[index]=teacher_obj Manage_sys.data_flush (Teacher_data) def accidents (self): "" "classroom accident, and the corresponding teacher's assets to make corresponding adjustments: return:" "" "Print (' slot, today is not the class,%s teacher to enlarge        Health care of '%self.teacher_name ' Print (5* ' big health ... ') time.sleep (1) Print (' Money-refund refund!!! ')        Teacher_obj,index=manage_sys.sub_match_teacher (self.classes) #执行老师对象的资产减少方法 teacher_obj.teach_accidents () Teacher_data=manage_sys.data_read () teacher_data[index]=teacher_obj Manage_sys.data_flush (teacher_Data) #定义学生的类class student:def __init__ (self,name,pwd): Self.name=name self.pwd=pwd Self.subject_c Lasses=[]

core/manage_sys.py

#!/usr/bin/env python#-*-coding=utf-8-*-# Auther:ccorz mail:[email protected] Blog:http://www.cnblogs.com/ ccorz/# Github:https://github.com/ccorzorzimport Sys,os,pickle,prettytable,timebase_dir=os.path.dirname ( Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (Base_dir) from conf.setting import * #定义登录状态的常量LOGIN_        State=falsedef Check_login (func): "" "Adorner, Judge administrator rights:p Aram Func:: Return:" "" Def Inner (*args,**kwargs): If login_state: #判断是否已登录 res=func (*args,**kwargs) return res else:print (' program requires login to execute! ') ) return Innerdef Data_read (): "" "Teacher db Read function: return: Read result" "" Data=pickle.load (Open (Manage_data_file, ' RB ') return datadef Data_flush (args): "" "writes the modified new teacher class data:p Aram args: Revised teacher data: Return:" "" Pickle.dump ( Args,open (Manage_data_file, ' WB ')) def subject_data_read (): "" reads data from Course class: return: Read result "" "Subject_data=pickl E.load (Open (Subject_data_file, ' RB ')) return subject_datadef suBject_data_flush (args): "" "writes modified course class data:p Aram args: Modified data: Return:" "" Pickle.dump (Args,open (subject_d Ata_file, ' WB ') def Sub_match_teacher (sub_classes): "" "matches teacher's name in course class and teacher object in teacher class data:p Aram sub_classes: Course Name: Return        : Match the Teacher object and the corresponding index "" "#读取课程数据 Subject_data=subject_data_read () #遍历课程数据, find the name of the class for item in Subject_data: If Sub_classes==item.classes:teac_name=item.teacher_name #遍历教师数据, find the corresponding teacher's object and subscript value Teacher_data=data_ Read () for item in Teacher_data:if Item.name==teac_name:teacher_ob=item Index=teacher_da Ta.index (item) return Teacher_ob,indexdef Teacher_name (): "" "generates the Teacher Name list function: return: Returns the Name list" "" Manage_data =data_read () teacher_list=[] for teacher in Manage_data:teacher_list.append (teacher.name) # print (teacher _list) return Teacher_listdef subject_name (): "" "Generate Course Name list function: Return: Course Name list" "" Subject_data=subject_da Ta_read () Subject_lisT=[] for subject in Subject_data:subject_list.append (subject.classes) # print (subject_list) return SUBJEC T_list@check_logindef Creat_teacher (): "" "Create Teacher Function: return:" "#读取教书数据 manage_data=data_read () teache    R_list=teacher_name () name=input (' Input teacher Name: ') if name in Teacher_list: #判断是否已存在此教师 print (' Existing teacher: Data of%s '%name)                Else:while true:age=input (' Please enter teacher Age: ') if Age.isdigit (): Age=int (Ages) Break else:print (' input wrong, please re-enter ') favor=input (' Please input teacher hobby and good at, can choose multiple, use comma separated: ') #调用教师类创建教师, and give corresponding genus Sex Docor_name=teacher (Name,age,favor) manage_data.append (docor_name) Data_flush (manage_data) PR Int (' Teacher%s has been created successfully! ')    %name) @check_logindef creat_subject (): "" "Create a Course Function: return:" "#读取课程数据 subject_data=subject_data_read () Subject_list=subject_name () classes=input (' Please enter course Name: ') #判断是否有此课程 if classes in Subject_list:print (' already Subject to%s course '%Classes) else:while true:value=input (' Please enter lesson fee: ') if Value.isdigit (): Value        =int (value) break else:print (' input wrong, please reenter. ') While True:print (' Please select the instructor '. Center () manage_data=show_teachers () num=input (' Please select teacher                    Should be the serial number ') if Num.isdigit (): Num=int (num) if num < Len (manage_data): Teacher_name=manage_data[num].name #调用课程类创建课程, and gives the corresponding attribute Subject_obj=subject (CLA Sses,value,teacher_name) subject_data.append (subject_obj) Subject_data_flush (subject            _data) Break else:print (' input wrong, please re-enter. ') Else:print (' Input wrong, please re-enter. ')     # @check_logindef Show_teachers (): "" "Displays all teacher information functions: return:" "" #遍历教师数据文件, and print the corresponding information Manage_data=data_read () Row=prettytable. Prettytable () row.field_names=[' serial number ', ' Teacher name ', ' age ', ' hobby ', ' current assets '' For teach in Manage_data:row.add_row ([Manage_data.index (teach), tea                                          Ch.name, Teach.age, Teach.favor,    Teach.asset]) print (row) return Manage_datadef show_subject (): "" "Displays all course information : Return: "" "#遍历课程数据 and display the corresponding information Subject_data=subject_data_read () row=prettytable. Prettytable () row.field_names=[' serial number ', ' Subject name ', ' Lesson fee ', ' instructor ', ' for subject in Subject_data:row.add_row ([subject_d Ata.index (subject), subject.classes, Subject.value, Subject.te Acher_name]) print (row) return Subject_datadef logout (): "" "Exit system function: Return:" "Exit (' program exits! ') Def menu (): "" "Print Menu Function: return:" "row=prettytable.   Prettytable () row.field_names=[' Create teacher ', ' Create course ', ' View all teachers ', ' View all courses ', ' Exit Program '] Row.add_row ([0,1,2,3, ' q&quit ']) Print (ROW) def login (): "" "Login Function: Return:" "" User=input (' Enter administrator user name: ') pwd=input (' Please enter password: ') if (User A        nd pwd) = = ' Admin ': #登录成功后修改全局变量 global login_state login_state=true print (' Login successful! ')        return login_state Else:print (' username or password is wrong! ') return False@check_logindef Main (): "" "main function, System entry: return:" "" while True:menu () #打印菜单后, function name List to allow the user to select, and then execute the corresponding function Menu_list=[creat_teacher,creat_subject,show_teachers,show_subject,logout] inp=input (' Please select Operation corresponding serial number: ') if Inp.isdigit (): Inp=int (INP) if INP < Len (menu_list): Menu_li ST[INP] () time.sleep (1) elif InP = = ' Q ' or INP = = ' Quit ': Logout () else:print (' Input error , please re-enter. ')

Core/student.py:

#!/usr/bin/env python#-*-coding=utf-8-*-# Auther:ccorz mail:[email protected] Blog:http://www.cnblogs.com/ ccorz/# Github:https://github.com/ccorzorzimport Sys,os,pickle,prettytablebase_dir=os.path.dirname ( Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (Base_dir) from conf.setting import *from core Import manage_sys# user=nonedef Student_data_read (): "" "reads Student data: return: Read student data" "" Student_data=pickle.load (ope    N (student_data_file, ' RB ')) return student_datadef Student_data_flush (args): "" "Refresh student data:p Aram args: New student data    : Return: "" "Pickle.dump (Args,open (student_data_file, ' WB ')) def student_name ():" "" Generate Student Login user Name list: return: "" "Student_data=student_data_read () student_name_list=[] for item in Student_data:student_name_list.appe nd (item.name) return student_name_listdef regist (): "" "Register Function: Return:" "" Student_data=student_data_read   () Student_name_list=student_name () name=input (' Please enter your username: ') If name in Student_name_list: #判断是否存在用户名 print (' Existing User:%s '%name) else:pwd=input (' Please enter your password: ') For I in range (3): Pwd_again=input (' Confirm Registration password: ') if Pwd_again = = Pwd:print ('%s registered successfully! ') %name) #调用学生类生成学生对象 and written to the Student class database Student_obj=student (NAME,PWD) Student_data.app End (Student_obj) Student_data_flush (student_data) Break Else:prin T (' Password is incorrect, please re-enter, remaining attempts%s '% (2-i)) def s_login (): "" "" "Student Login Function: return:" "#读取学生类数据库和学生姓名列表, two lists of subscript match Studen T_data=student_data_read () Student_name_list=student_name () name=input (' Please enter your user name: ') if name not in student_name_l Ist:print (' no%s user name. ')            %name) else:for I in range (3): Pwd=input (' Please enter password for user%s: '%name ') #如果输入的密码与学生类中的密码匹配            If Pwd==student_data[student_name_list.index (name)].pwd:global USER user=name    Print (' Login successful!!! ') return True else:print (' Password checksum failed, number of attempts left:%s '% (2-i)) def choice_subject (): "" "Select Course Function: return:" "#读 Take the Student class database and student Name list, two list of subscript matches Student_data=student_data_read () student_name_list=student_name () #读取课程类数据库 subject_ Data=manage_sys.show_subject () InP = input (' Please select the serial number corresponding to the subject name ') if Inp.isdigit (): Inp=int (INP) if INP < Len (subject_data): #如果输入序列符合条件, take the course object SUBJECT=SUBJECT_DATA[INP] #学生类对象中取到课程列表 in the course database, if            There are course tips, if there is no same course, add to the course list and write to Data Student_subject_list=student_data[student_name_list.index (USER)].subject_classes If subject.classes in Student_subject_list:print (' You already have the%s discipline in your timetable! ') %subject.classes) else:student_subject_list.append (subject.classes) student_data _flush (student_data) print (' Course associated successfully ') else:print (' Choose wrong, re-enter ') else:print (' Choose wrong, re-enter ') def has_sub Ject (): "" "Displays the selectedCourse function: Return: "" "#读取学生类数据库和学生姓名列表, two-list subscript matches student_data=student_data_read () Student_name_list=student_na    Me () #读取学生对象中的对应课程列表信息, print all course Information Student_subject_list=student_data[student_name_list.index (USER)].subject_classes Row=prettytable. Prettytable () row.field_names=[' serial number ', ' Course name '] for item in Student_subject_list:row.add_row ([Student_subject_li St.index (item), item]) print (row) return Student_subject_listdef s_logout (): Sys.exit (' program quit! ') Def show_menu (): "" "After login menu information function: return:" "row=prettytable. Prettytable () row.field_names=[' Select Course ', ' View selected Course ', ' class ', ' teaching accident ', ' exit Program '] Row.add_row ([0,1,2,3, ' 3&q&quit ']) prin    T (ROW) def attend (): "" "Class Function: Return:" "#读取学生类数据库和学生姓名列表, subscript for two lists matches Student_data=student_data_read () Student_name_list=student_name () Student_subject_list=student_data[student_name_list.index (USER)].subject_ Classes for Index,item in Enumerate (student_subject_list): Print (Index,itemInp=input (' Please select the course corresponding serial number: ') #选择上课的目标课程 if Inp.isdigit (): Inp=int (INP) if INP < Len (student_subjec            t_list): #如果符合序列号标准 #确认课程名称 SUBJECT_CLASSES=STUDENT_SUBJECT_LIST[INP] #读取课程对象数据                Subject_data=manage_sys.subject_data_read () #确认相应的课程对象 for item in Subject_data: If Item.classes==subject_classes:subject_obj=item #调用课程对象的上课方法 Subject_obj.att End_class () else:print (' Wrong choice ') else:print (' Wrong choice! ') Def s_accidents (): "" "Teaching accident function, same as class function: return:" "Student_data=student_data_read () student_name_list=st Udent_name () Student_subject_list=student_data[student_name_list.index (USER)].subject_classes for Index,item in ENU Merate (student_subject_list): Print (Index,item) inp=input (' Please select the serial number for the course: ') if Inp.isdigit (): Inp=int (in P) If InP < Len (student_subject_list): subject_classes=student_subJECT_LIST[INP] Subject_data=manage_sys.subject_data_read () for item in Subject_data: If Item.classes==subject_classes:subject_obj=item #调用课程对象的教学事故方法 SUBJECT_OBJ.ACC idents () else:print (' Wrong choice ') else:print (' Wrong choice! ') Def main2 (): "" "After login Menu selection interface: return:" "#将函数名形成列表, select Execute function MENU=[CHOICE_SUBJECT,HAS_SUBJECT,ATTEND,S_ACC             Idents,s_logout] While True:show_menu () inp=input (' Select the operation corresponding to the serial number: ') if inp = = ' Q ' or INP = = ' Quit ':                S_logout () elif inp.isdigit (): Inp=int (INP) if INP < Len (menu):    MENU[INP] () else:print (' input wrong, please reenter ') else:print (' input wrong, please reenter ~ ') def main (): "" "Main function entry: return:            "" "Print (' 1. Login 2. Register") inp=input (' Please select the appropriate operation serial number: ') if InP = = ' 1 ': Res=s_login () If res: Main2 () elif inp== ' 2 ': Regist () else:print (' Wrong choice! System exit ') # if __name__ = = ' __MAIN__ ': # Main () 

The data directory is a database file, which is created directly by hand. Call it off!

Day7 Homework: Course selection system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.