Python学习笔记 8

1. 参数解包

在我们调用函数的时候一般会传入多个参数,但是一个个传的话明显很费事,所以我们可以将参数打包传入然后让函数去进行参数解包,以下为相关的一些操作

    #定义一个接受打包参数的函数
    In [15]: def halo(**kwargs):
       ....:     print kwargs
       ....:     

    In [16]: d={'name':'lockey','age':23}
    #将定义的字典参数传入,结果报错,原因是参数问题
    In [17]: halo(d)
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-17-969fe2bd5d97> in <module>()
    ----> 1 halo(d)

    TypeError: halo() takes exactly 0 arguments (1 given)
    #尝试将参数硬打包传入
    In [18]: halo(x=d)
    {'x': {'age': 23, 'name': 'lockey'}}

    #错误的引用方式
    In [19]: halo(*d)
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-19-d892cb70e2c6> in <module>()
    ----> 1 halo(*d)

    TypeError: halo() takes exactly 0 arguments (2 given)

    #正确的打包方式
    In [20]: halo(**d)
    {'age': 23, 'name': 'lockey'}

2. 创建生成器的 xrange

In [21]: lst = (i for i in xrange(1,100))

In [22]: lst
Out[22]: <generator object <genexpr> at 0x1b8dc80>
#由上边的结果可以看出xrange产生的为一个生成器对象

In [23]: lst.next()
Out[23]: 1

In [24]: lst.next()
Out[24]: 2

In [25]: lst.next()
Out[25]: 3

3. 高阶函数(Higher-order functions)HOFs

一个高阶函数就是以一个或多个函数为参数并返回一个函数的函数。与利用itertools库结合函数以产生新的迭代器的方法类似,高阶函数可以前后连接与结合函数,使我们可以做很多有趣的抽象。

Python中一些有用的高阶函数包含在functools中,而另一些则是内建的。通常认为map(), filter()以及functools.reduce()是python中高阶函数的基础模块,并且绝大多数的函数式语言使用这些函数作为他们的基础(函数的名称偶尔会有不同)。与map/filter/reduce几乎一样基础的基础模块是柯里化(currying)。在python中,柯里化对应的函数是包含在functools模块中的partial(),这个函数以其它函数为参数,但其它函数中的零个或更多参数已经给定,从而使得返回的函数的参数减少,运行起来与给定参数的其它函数类似。

内建函数map()与filter()与解析式(comprehension)等价(尤其是考虑到目前生成器解析式(generator comprehension)已经可用),但是很多python程序员认为解析式可读性更强一些。例如,以下表达式是等价的:

transformed = map(tranformation,iterator)
||
transformed = (transformation(x) for x in iterator)

filtered = filter(predicate,iterator)
||
filtered = (x for x in iterator if predicate(x))

函数functools.reduce()非常通用,强大但是想发挥其全部威力的技巧却相当微妙。它以前后相继的迭代器对象为参数,并以某种方式将它们结合起来。reduce()最常见的用法可能已经由内建函数sum()涵盖了,sum()函数实际上只是以下形式的简写:

from functools import reduce
total = reduce(operator.add,it,0)
#total = sum(it)

可能显然也可能不显然的是,map()与filter()也是reduce()的特殊情形,也即:

>>> add5 = lambda n: n+5
>>> reduce(lambda l,x: l+[add5(x)],range(10),[])
[5,6,7,8,9,10,11,12,13,14]
>>> # simpler: map(add5,range(10)
>>> isOdd = lambda n: n%2
>>> reduce(lambda l,x: l+[x]if isOdd(x) else l, range(10),[])
[1,3,5,7,9]
>>> # simpler: filter(isOdd,range(10))

这些reduce()表达式令人困惑,但是它们说明了这个函数具有多么强大的通用性:任何对前后相继元素的计算都可以表达为reduce()的形式。

也有一些常用的高阶函数不包含在python的原始库中,但是它们可以通常容易编写 (并且有些第三方库包含了这些函数)。不用的库以及不同的语言可能使用不同的函数名称,但是它们都拥有类似的功能。

内建函数all()与any()可以用于查询迭代器中的元素是否满足谓词条件。但是同样方便的是查询特定的数据是否满足任意或任何的谓词条件组合。

4. 编程时间

4.1 通过面向对象的方式实现队列和栈的数据结构;

关于栈:

栈是一种特殊的线性表。其特殊性在于限定插入和删除数据元素的操作只能在线性表的一端进行。其最大的特性就是后进先出(Last In First Out),所以也简称为LIFO线性表。

栈的基本运算有六种:

构造空栈:InitStack(S)、

判栈空: StackEmpty(S)、

判栈满: StackFull(S)、

进栈: Push(S,x)、可形象地理解为压入,这时栈中会多一个元素

退栈: Pop(S) 、 可形象地理解为弹出,弹出后栈中就无此元素了。

取栈顶元素:StackTop(S),不同与弹出,只是使用栈顶元素的值,该元素仍在栈顶不会改变。

通常栈有顺序栈和链栈两种存储结构,在顺序栈中有”上溢”和”下溢”的概念,链栈则没有上溢的限制,它就象是一条一头固定的链子,可以在活动的一头自由地增加链环(结点)而不会溢出,链栈不需要在头部附加头结点,因为栈都是在头部进行操作的,如果加了头结点,等于要在头结点之后的结点进行操作,反而使算法更复杂,所以只要有链表的头指针就可以了

关于队列

队列(Queue)也是一种运算受限的线性表,它的运算限制与栈不同,是两头都有限制,插入只能在表的一端进行(只进不出),而删除只能在表的另一端进行(只出不进),允许删除的一端称为队尾(rear),允许插入的一端称为队头 (Front),队列的操作原则是先进先出的,所以队列又称作FIFO表(First In First Out)

队列的基本运算也有六种:

置空队 :InitQueue(Q)

判队空: QueueEmpty(Q)

判队满: QueueFull(Q)

入队 : EnQueue(Q,x)

出队 : DeQueue(Q)

取队头元素: QueueFront(Q),不同与出队,队头元素仍然保留。

队列也有顺序存储和链式存储两种存储结构,前者称顺序队列,后者为链队。

说着这么多,写点代码吧:

#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
file:ooQueue.py
date:17-9-5 上午11:21
author:lockey
email:lockey@123.com
desc:面向对象实现的队列
'''
class Queue(object):
    def __init__(self):
        self.queue = []

    def eleIn(self,*args):
        self.queue.extend(args)

    def eleOut(self):
        if self.queue == []:
            return None
        else:
            return self.queue.pop(0)

    def eleShow(self):
        if self.queue == []:
            print 'Queue is empty!'
            return
        print 'Element in queue: '
        queues = ''
        for i in self.queue:
            queues += str(i)
        print queues
    def eleEmpty(self):
        if self.queue == []:
            print 'Empty queue!'
            return True
        print 'Queue not empty!'
        return False

    def eleHead(self):
        if self.eleEmpty():
            print 'Empty queue, no head show!'
            return None
        print 'Queue head is: ',self.queue[0]
    def eleTail(self):
        if self.eleEmpty():
            print 'Empty queue, no tail show!'
            return None
        print 'Queue tail is: ',self.queue[-1]
    def eleLen(self):
        if self.queue == []:
            print 'No element in queue!'
            return
        print 'Lenght of queue is: ',len(self.queue)

4.2 通过面向对象的方式实现一个简单的学校管理系统
实现的功能有以下:

  • 管理员进行学校创建、用户(管理员、老师、学生)管理(添加、删除)、课程添加等操作
  • 学生登录系统并学习、缴费、修改密码、查看自己的信息
  • 老师登录系统并讲课、查看自己所教课程的学生信息、查看自己信息、改密码等

python代码实现:

# -*- coding: UTF-8 -*-
'''
Created on 2017年9月3日
Running environment:win7.x86_64 eclipse python3
@author: Lockey
'''

import time
import datetime
from test.datetimetester import DAY

#定义一个学校类包含私有属性以及成员方法
class School(object):
    'This is class for School model'
    __admins = {}
    __teachers = {}
    __students = {}
    __courses = {}
    #初始化类
    def __init__(self):
        pass
    #激活、真正创建一个学校实例   
    def schoolactivate(self,school_name,school_location,school_motto):
        self.__school_name = school_name
        self.__school_location = school_location
        self.__school_motto = school_motto
    #添加系统管理员   
    def adminAdd(self,adminname,obj):
        self.__admins.setdefault(adminname,obj)
        return True
    #获得系统管理员信息
    def getAdmins(self):
        return self.__admins
    #获取学校成员如老师和学生的信息
    def getUser(self,usertype):
        if usertype == 'teacher':
            return self.__teachers
        elif usertype == 'student':
            return self.__students
        else:
            return False
    #添加课程
    def addCourse(self):
        courses = self.getCourses()
        totalCourses = len(courses)
        cname = ''; cprice = ''; ctime = ''
        try:
            while True:
                if cname == '':
                    cname = input('Please input your course name : ')
                    if cname in courses:
                        cname = ''
                        print('Courses already exists!')
                        return
                    if cname == '':
                        print('course name can not be blank, please reinput!')
                        continue

                if cprice == '':
                    cprice = input('Please input your course price : ')
                    if cprice == '':
                        print('course price can not be blank, please reinput!')
                        continue
                    try:
                        if 0> int(cprice) >100000:
                            print('Illegal price value, too high price againsts the law!')
                            cprice = ''
                            continue
                    except:
                        cprice = ''
                        print('Illegal price value, number is required!')
                        continue
                if ctime == '':   
                    ctime = input('Please input your course time (eg:2017-09-03): ')
                    if ctime == '':
                        print('course time can not be blank, please reinput!')
                        continue
                    if ctime.count('-') != 2:
                        print('Time format illegal!')
                        ctime = ''
                        continue
                    if not valid_date(ctime):
                        print('Time format illegal!')
                        ctime = ''
                        continue
                break
            cnumber = 'course'+str(totalCourses+1)
            #创建课程实例
            course = Course(cnumber,cname,cprice,ctime)
            self.__courses.setdefault(cname,course)
            self.__students.setdefault(cname)
            print('Course %s successfully added!'%cname)
            course.showInfo()
            return True
        except:
            return False
    #获取课程信息
    def getCourses(self):
        return self.__courses
    #招收学生
    def addStudent(self):
        courses = self.__courses
        students = self.__students
        sname = ''; sage = ''; sgender = ''; sclassof = ''
        while True:
            if sname == '':
                sname = input('Please input student name : ')
                if sname == '':
                    print('student name can not be blank, please reinput!')
                    continue

            if sclassof == '':
                sclassof = input('Please input student course : ')
                if sclassof not in courses:
                    courseLst = []
                    for item in courses:
                        courseLst.append(item)
                    print('No such course to attend, please input one of following items as your course!\n')
                    print(courseLst)
                    sclassof = ''
                    continue
            classStudents = self.__students[sclassof]
            if classStudents and sname in classStudents:
                print('Student {} already in class {}'.format(sname, sclassof))
                return False

            if sage == '':
                sage = input('Please input student age(6-120) : ')
                if sage == '':
                    print('student age can not be blank, please reinput!')
                    continue
                try:
                    age = int(sage)
                    if 0< age <=120:
                        pass
                    else:
                        sage = ''
                        print('Illegal human age, are your a neuropath!!')
                        continue
                except:
                    sage = ''
                    print('Illegal human age, number within 10000 is required!')
                    continue
            if sgender == '':   
                sgender = input('Please input student gender (male|female): ')
                if sgender == '':
                    print('student gender can not be blank, please reinput!')
                    continue
                if sgender == 'male' or sgender == 'female':
                    continue
                else:
                    print('invalid gender!')
                    sgender = ''
                    continue

            break

        fees = - int(courses[sclassof].price)
        try:
            studentTotal = len(students[sclassof])
        except:
            studentTotal = 0
        finally:
            studentno = 'student'+sclassof+str(studentTotal+1)
                #创建学生实例
            student = Student(sname, 'student', sage, sgender, sclassof, studentno,fees)
            try:
                if len(self.__students[sclassof]):
                    self.__students[sclassof].setdefault(sname,student)
            except:
                self.__students[sclassof]={sname:student}  
            print('Student %s successfully added, infos are as below:'%sname)
            course = courses[sclassof]
            student.showInfo(course)
            return True

    def deleteUser(self):
        while True:
            type = input('Please input user type [(a)dmin,(t)eacher,(s)tudent] (Q to quit): ')
            type=type.lower()
            if type == 'q':
                break
            if type not in 'ats':
                print('User type does not exist!')
                return

            if type == 'a':
                userDict = self.__admins
            elif type == 't':
                userDict = self.__teachers
            else:
                classof = input('Please input student class: ')
                if classof not in self.__courses:
                    print('No such class!')  
                    continue
                userDict = self.__students[classof]
            username = input('Please input username to delete: ')
            if username in userDict:
                if username == 'admin':
                    print('Operation forbidden, super administrator can not be destroyed!')
                    continue
                if type == 'a' or type == 't':
                    del userDict[username]
                    print('User %s successfully deleted!'%username)  
                    continue
                if userDict[username].feestate > 0:
                    refund = input('Current student has paid the fees, sure to refund and delete(Y/N): ')
                    if refund in 'nN':
                        print('Cancel deleting student %s'%username)
                        continue
                del userDict[username]
                print('Student %s successfully deleted!'%username)
                continue
            print('User %s does not exist!'%username) 

    #招收讲师
    def addTeacher(self):
        teachers = self.getUser('teacher')
        tname=''; tage=''; tgender=''; tcourse=''; tsalary=''
        try:
            while True:
                    if tname == '':
                        tname = input('Please input teacher name : ')
                        if tname in teachers:
                            tname = ''
                            print('teacher already exists!')
                            return
                        if tname == '':
                            print('teacher name can not be blank, please reinput!')
                            continue

                    if tage == '':
                        tage = input('Please input teacher age(6-120) : ')
                        if tage == '':
                            print('teacher age can not be blank, please reinput!')
                            continue
                        try:
                            age = int(tage)
                            if 0< age <=120:
                                pass
                            else:
                                tage = ''
                                print('Illegal human age, are your a neuropath!!')
                                continue

                        except:
                            tage = ''
                            print('Illegal human age, number within 10000 is required!')
                            continue
                    if tgender == '':   
                        tgender = input('Please input teacher gender (male|female) : ')
                        if tgender == '':
                            print('teacher gender can not be blank, please reinput!')
                            continue
                        if tgender == 'male' or tgender == 'female':
                            continue
                        else:
                            print('invalid gender!')
                            tgender = ''
                            continue
                    if tcourse == '':
                        courses = self.getCourses()
                        tcourse = input('Please input teacher course : ')
                        if tcourse == 'quit':
                            return
                        if tcourse not in courses:
                            courseLst = []
                            for item in courses:
                                courseLst.append(item)
                            print('No such course to attend, please input one of following items as your course!\n')
                            print(courseLst)
                            tcourse = ''
                            continue

                    if tsalary == '':   
                        tsalary = input('Please input teacher salary : ')
                        if tsalary == '':
                            print('teacher salary can not be blank, please reinput!')
                            continue
                        try:
                            if int(tsalary):
                                pass
                        except:
                            print('Illegal salary value, number is required!')
                            tsalary = ''
                            continue
                    break
            totalteacher = len(teachers)
            teacherno = 'teacher'+str(totalteacher+1)
            #创建老师实例
            teacher = Teacher(tname, 'teacher',tage, tgender, tcourse, tsalary, teacherno)
            self.__teachers.setdefault(tname,teacher)
            print('Teacher %s successfully added, infos as below:'%tname)
            course = courses[tcourse]
            teacher.showInfo(course)
            return True
        except:
            return False
    #查看学校信息
    def getSchoolInfo(self):
        ret = (self.__school_name,self.__school_location,self.__school_motto) 
        return ret  
#定义课程类
class Course(object):
    def __init__(self,cnumber,cname,cprice,ctime):
        self.number = cnumber
        self.name = cname
        self.price = cprice
        self.time = ctime
    #定义课程显示的方法
    def showInfo(self):
        print("""
        Infomation for course {}

            number : {}
            name : {}
            price : {}
            time: {}
            """.format(self.name, self.number, self.name, self.price, self.time))
#定义学校成员类,作为老师和学生的基类
class Member(object):
    def __init__(self,name,password,age,gender,*arg):
        self.name = name
        self.password = password
        self.age = age
        self.gender = gender

    def showInfo(self):
       pass
    def changePassword(self):
        orign = False
        while True:
            if orign == False:
                password = input('Please input old password to authenticate: ')
                if password != self.password:
                    print('Original password not correct, try again!')
                    continue
                orign = True
            password1 = input('Please input new password(Q to quit): ')    
            if password1 in 'Qq':
                return False

            if password1 == self.password:
                print('Passwords can not be the same as the old one, try again!')
                continue

            if len(password1) < 6:
                print('Passwords must more than 5 characters , try again!')
                continue

            password2 = input('Please confirm password: ')
            if password1 != password2:
                print('Passwords not equal, try again!')
                continue
            self.password = password1
            print('Passwords successfully changed!')
            break
#定义老师类
class Teacher(Member):

    def __init__(self,name,password,age,gender,*arg):
        super().__init__(name,password,age,gender)
        self.course = arg[0]
        self.salary = arg[1]
        self.number = arg[2]

    def showInfo(self,obj):
        print("""
        Infomation for teacher {}

            number : {}
            name : {}
            age : {}
            gender: {}
            course : {}
                course number:{}
                course price :{}
                course time  :{}
            salary : {}
            """.format(self.name, self.number, self.name, self.age, self.gender, self.course, obj.number, obj.price, obj.time, self.salary))
    #老师讲课的方法函数
    def giveLecture(self):
        print('Course {} start ...'.format(self.course))
        for i in range(5,0,-1):
            time.sleep(1)
            print('Course {} will over after {} seconds...'.format(self.course,i))
            i = i - 1
        print('Course {} over ...'.format(self.course))
    #老师查看自己所带课程的学生信息
    def viewStudents(self,students):
                print("""
        Student attending {} are as below""".format(self.course))
                print("""
    number   name   age   gender   class""")
                for stu in students:
                    print('    {} {}      {}     {}        {}'.format(stu.number,stu.name,stu.age,stu.gender,stu.classof))
#定义学生类    
class Student(Member):

    def __init__(self,name,password,age,gender,*arg):
        super().__init__(name,password,age,gender)
        self.classof = arg[0]
        self.number = arg[1]
        self.feestate = arg[2]
    #定义学生学习的方法
    def learning(self):
        print('{} start learning ...'.format(self.name))
        for i in range(5,0,-1):
            time.sleep(1)
            print('{} keep learning ...'.format(self.name))
            i = i - 1
        print('{} stop learning and go to date ...'.format(self.name))
    #定义学生缴费的方法函数
    def payFees(self):
        if self.feestate < 0:
            self.feestate *= -1
            print('Fees paid off!')
            return
        else:
            print('Fees already paid!')
            return

    def showInfo(self,obj):
        print("""
        Infomation for student {}

            number : {}
            name : {}
            age : {}
            gender : {}
            feeState : {}
            class : {}
                course number:{}
                course price :{}
                course time  :{}
            """.format(self.name, self.number, self.name, self.age, self.gender, self.feestate, self.classof,obj.number, obj.price, obj.time))
#用来判断输入的日期是否合规范
def valid_date(dateStr):
    try:
        year, month, day = map(int,dateStr.split('-'))
        mDay = [31,28,31,30,31,30,31,31,30,31,30,31]
        if 2017<=year<=2038 and 1<=month<=12 and 1<=day<=31:
            if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
                mDay[1] = 29
            if day > mDay[month-1] :
                return False
            return True
        return False      
    except:
        return False
#判断当前时段,返回一个时间段的代表值作为问候语的一部分 
def period():
    currentTime = datetime.datetime.now()
    hour = currentTime.hour
    if 6 <= hour < 12:
        return 'morning!'
    if 12 <= hour < 14:
        return 'midday!'  
    if 14 <= hour < 18:
        return 'afternoon!'
    if 18 <= hour < 20:
        return 'evening!'
    else:
        return 'night'
#所有相关用户的登录函数,用来进行登录限制
def userloginCheck(usertype,obj):
    if usertype == 'admin':
        admins = obj.getAdmins()
        userDict = admins
    else:
        userDict = obj.getUser(usertype)
        if usertype == 'student':
            course = input('Please input your class: ')
            if course in userDict:
                userDict = userDict[course]
            else:
                print('No such class!')
                return False   
    loginuser = False
    userAttempt = 0
    while userAttempt < 3:

        username = input('Please input username: ')
        userAttempt += 1
        if not userDict.get(username):
            print('Username not exist!')
            continue
        password = input('Please input password: ')
        if password == userDict[username].password:
            passwordCheck = checkPassword(usertype,userDict[username],password)
            if passwordCheck:    
                loginuser = userDict[username]
            break
        else:
            print('Username or password not correct!')

    if userAttempt >= 3:
        print('User {} has tried 3 times, please login later!'.format(username)) 
    return loginuser
#用户初次登录强制修改密码函数
def checkPassword(usertype,obj,oldpwd):
    defaultPwd={'admin':'admin','teacher':'teacher','student':'student'}
    if defaultPwd[usertype] == oldpwd:
        print('For first logged in user, password should be changed!')
        while True:
            password1 = input('Please input new password: ')    
            if password1 in 'Qq':
                return False

            if password1 == oldpwd:
                print('Passwords can not be the same as the old one, try again!')
                continue

            password2 = input('Please confirm password: ')
            if password1 != password2 and password1 != '':
                print('Passwords not equal, try again!')
                continue

            if len(password1) < 6:
                print('Passwords must more than 5 characters , try again!')
                continue

            obj.password = password1
            break
    return True
#管理员管理模块函数
def systemManage(user,school):
    greeting = period()
    oplist = """
    Good {} administator [ {} ]

            menu lists

        (M) : school manage
        (C) : course Eroll
        (T) : teacher Eroll
        (S) : student Eroll
        (VT) : view teachers 
        (VS) : view students
        (VC) : view courses
        (P) : change password
        (A) : add administrator
        (D) : delete user(admin/teacher/student)
        (Q) : quit
            """.format(greeting, user.name)
    print(oplist)
    while True:
        userChoice = input('Please input your operation (o to  show menu): ')
        if userChoice in 'Mm':
            schoolInfo = school.getSchoolInfo()
             #学校信息管理
            print("""
    Information for school {}

          name: {}
          location: {}
          motto:{}
        """.format(schoolInfo[0],schoolInfo[0],schoolInfo[1],schoolInfo[2]))
            continue
        if userChoice in 'oO':
            print(oplist)
            continue
        if userChoice in 'Cc':
            result =  school.addCourse()
            if not result:
                print('Course adding failed!')
            continue

        elif userChoice in 'Tt':
            result = school.addTeacher()
            if not result:
                print('Teacher enrolling failed!')
            continue

        elif userChoice in 'Ss':
            result = school.addStudent()
            if not result:
                print('Student enrolling failed!')
            continue

        elif userChoice in 'VSvsVsvS':
            studentDict = school.getUser('student')
            if len(studentDict) > 0:
                try:
                    for course in studentDict:
                        if len(studentDict[course]) > 0:                       
                            print("""
            Students attending {} are as below""".format(course))
                            print("""
        number   name   age   gender   class""")
                            for student in studentDict[course]:
                                stu = studentDict[course][student]
                                print('       {} {}      {}     {}        {}'.format(stu.number,stu.name,stu.age,stu.gender,stu.classof))
                except:
                    print('\nNo students info to show!\n')
            else:
                print('\nNo students info to show!\n')
        elif userChoice in 'VTvtVtvT':
            teachers = school.getUser('teacher')
            try:
                if len(teachers) > 0:     
                    print("""
                Teachers information are as below:

            number   name   age   gender   course   salary""")
                    for item in teachers:
                        teacher = teachers[item]
                        print('       {} {}      {}     {}        {}         {}'.format(teacher.number,teacher.name,teacher.age,teacher.gender,teacher.course,teacher.salary))
                else:
                    print('\nNo teachers info to show!\n')
            except:
                print('No teachers info to show!')
        elif userChoice in 'VCvcVcvC':
            courses = school.getCourses()
            if len(courses) > 0:
                print("""
            Courses information are as below:

        number   name   price   time""")
                for item in courses:
                    course = courses[item]
                    print('       {}  {}      {}      {}'.format(course.number,course.name,course.price,course.time))
            else:
                print('\nNo courses info to show!\n')
        elif userChoice in 'pP':
            user.changePassword()
            continue
        elif userChoice in 'aA':
            while True:
                    adminname = input('Please input administrator name(q to quit) : ')
                    if adminname in 'qQ':
                        break
                    if adminname in school.getAdmins():
                        print('Administrator %s already exists!'%adminname)
                        continue   
                    admin = Member(adminname,'admin','admin','admin')
                    result = school.adminAdd(adminname, admin)
                    if result:
                        print('Administrator successfully added with default password "admin"! ')
                        break
                    print('Failed to add administrator %s!'%adminname)
            continue
        elif userChoice in 'dD':
            school.deleteUser()
            continue
        elif userChoice in 'Qq':
            print('Administrator %s exited!'%user.name)  
            break
        else:
            print('No operation math your choice ({}) or operation forbidden(no shcool exists)!'.format(userChoice))
            continue

#老师登录函数     
def teacherLogin(obj):
    user = userloginCheck('teacher',obj)
    if user == False:
        return
    teacher = user
    teachCourse = teacher.course
    greeting = period()
    print("""
    Good {} teacher [ {} ]

            menu lists

        (G)  : give a lecture
        (VT) : view self information
        (VS) : view students attending class
        (C)  : change password
        (Q)  : quit
            """.format(greeting, user.name))
    while True:
        userChoice = input('Please input your operation: ')
        if userChoice in 'gG':
            teacher.giveLecture()
            continue
        elif userChoice in 'VTvtVtvT':
            courses = obj.getCourses()
            course = courses[teachCourse]
            teacher.showInfo(course)
            continue
        elif userChoice in 'VSvsVsvS':
            studentDict = obj.getUser('student')
            if len(studentDict) > 0:
                try:
                    if len(studentDict[teachCourse]) > 0:                       
                        print("""
        Students attending {} are as below""".format(teachCourse))
                        print("""
    number   name   age   gender   class""")
                        for student in studentDict[teachCourse]:
                            stu = studentDict[teachCourse][student]
                            print('       {} {}      {}     {}        {}'.format(stu.number,stu.name,stu.age,stu.gender,stu.classof))
                except:
                    print('\nNo students info to show!\n')
            else:
                print('\nNo students info to show!\n')
            continue
        elif userChoice in 'cC':
            teacher.changePassword()
            continue
        elif userChoice in 'qQ':
            print('Teacher %s exited!'%user.name)  
            break
        else:
            print('No operation math your choice ({})'.format(userChoice))
#学生登录函数        
def studentLogin(obj):
    user = userloginCheck('student',obj)
    if user == False:
        return
    student = user
    course = student.classof
    courses = obj.getCourses()
    greeting = period()
    print("""
    Good {}  [ {} ]

            menu lists

        (L) : Learning
        (P) : Pay the fees
        (S) : Self info show
        (C) : change password
        (Q) : quit
            """.format(greeting, user.name))
    while True:
        userChoice = input('Please input your operation: ')
        if userChoice in 'lL':
            student.learning()
            continue
        elif userChoice in 'pP':
            student.payFees()
            continue
        elif userChoice in 'sS':
            course = courses[course]
            student.showInfo(course)
            continue
        elif userChoice in 'cC':
            student.changePassword()
            continue
        elif userChoice in 'qQ':
            print('Student %s exited!'%user.name)  
            break
        else:
            print('No operation math your choice ({})'.format(userChoice))

#系统起始运行函数
def systemStart():
    adminFirstLogin = False
    admin = Member('admin','admin','admin','admin')
    school = School()
    school.adminAdd('admin', admin)
    menu = """
    Welcome to education manage system

            menu lists

        (M) : system manage
        (T) : teacher login
        (S) : student login
        (Q) : quit
            """
    print(menu)
    while True:
        userChoice = input('Please input your operation(input "O" for operation menu list) : ')
        if userChoice in 'oO':
            print(menu)
            continue
        if userChoice in 'Mm':
            loginUser = userloginCheck('admin',school)
            if loginUser == False:
                continue
            if adminFirstLogin:
                    systemManage(loginUser,school)
            else:
                print('There is no school exists, please create a school first!\n')
                schoolname = ''; schoollocation = ''; schoolmotto = ''
                while True:
                    if schoolname == '':
                        schoolname = input('Please input your school name : ')
                        if schoolname == '':
                            print('School name can not be blank, please reinput!')
                            continue

                    if schoollocation == '':
                        schoollocation = input('Please input your school location : ')
                        if schoollocation == '':
                            print('School location can not be blank, please reinput!')
                            continue

                    if schoolmotto == '':   
                        schoolmotto = input('Please input your school motto : ')
                        if schoolmotto == '':
                            print('School motto can not be blank, please reinput!')
                            continue
                    break
                school.schoolactivate(schoolname, schoollocation, schoolmotto)
                systemManage(loginUser,school)
                adminFirstLogin = True
                continue
        elif userChoice in 'Tt':
            if adminFirstLogin :
                teacherLogin(school)
            else:
                print('There is no school exists, please create a school first(iNput "m|M")!\n')
                continue
        elif userChoice in 'Ss':
            if adminFirstLogin :
                studentLogin(school)
            else:
                print('There is no school exists, please create a school first(iNput "m|M")!\n')
                continue
        elif userChoice in 'Qq':
            break
        else:
            print('No operation math your choice ({})'.format(userChoice))

    print('System exited!')
if __name__ == "__main__":
    systemStart()


运行结果示例:

    Welcome to education manage system

            menu lists

        (M) : system manage
        (T) : teacher login
        (S) : student login
        (Q) : quit

Please input your operation(input "O" for operation menu list) : m
Please input username: root
Username not exist!
Please input username: admin
Please input password: admin
For first logged in user, password should be changed!
Please input new password: redhat
Please confirm password: redhat
There is no school exists, please create a school first!

Please input your school name : Standford
Please input your school location : California
Please input your school motto : stand for

    Good afternoon! administator [ admin ]

            menu lists

        (M) : school manage
        (C) : course Eroll
        (T) : teacher Eroll
        (S) : student Eroll
        (VT) : view teachers 
        (VS) : view student
        (VC) : view student
        (Q) : quit

Please input your operation : m

    Information for school Standford

          name: Standford
          location: California
          motto:stand for

Please input your operation : c
Please input your course name : math
Please input your course price : 1200
Please input your course time : 2017-10-01
Course math successfully added!

        Infomation for course math

            number : course1
            name : math
            price : 1200
            time: 2017-10-01

Please input your operation : vc

            Courses information are as below:

        number   name   price   time
       course1  math      1200      2017-10-01
Please input your operation : t
Please input teacher name : lockey
Please input teacher age : 23
Please input teacher gender (male|female) : male
Please input teacher course : english
No such course to attend, please input one of following items as your course!

['math']
Please input teacher course : math
Please input teacher salary : 12300000
Teacher lockey successfully added, number is teacher1 !

        Infomation for teacher lockey

            number : teacher1
            name : lockey
            age : 23
            gender: male
            course : math
                course number:course1
                course price :1200
                course time  :2017-10-01
            salary : 12300000

Please input your operation : s
Please input student name : halo
Please input student age : sdf23423
Illegal human age, number within 10000 is required!
Please input student age : 18
Please input student gender (male|female): female
Please input student course : janpanese
No such course to attend, please input one of following items as your course!

['math']
Please input student course : math
Student halo successfully added, number is studentmath1 !

        Infomation for student halo

            number : studentmath1
            name : halo
            age : 18
            gender : female
            feeState : -1200
            class : math
                course number:course1
                course price :1200
                course time  :2017-10-01

Please input your operation : vt

                Teachers information are as below:

            number   name   age   gender   course   salary
       teacher1 lockey      23     male        math         12300000
Please input your operation : vc

            Courses information are as below:

        number   name   price   time
       course1  math      1200      2017-10-01
Please input your operation : vs

            Students attending math are as below

        number   name   age   gender   class
       studentmath1 halo      18     female        math
Please input your operation : q
User admin exited!
Please input your operation(input "O" for operation menu list) : o

    Welcome to education manage system

            menu lists

        (M) : system manage
        (T) : teacher login
        (S) : student login
        (Q) : quit

Please input your operation(input "O" for operation menu list) : t
Please input username: lockey
Please input password: teacher
For first logged in user, password should be changed!
Please input new password: redhat
Please confirm password: redhat

    Good afternoon! teacher [ lockey ]

            menu lists

        (G)  : give a lecture
        (VT) : view self information
        (VS) : view students attending class
        (Q)  : quit

Please input your operation: g
Course math start ...
Course math will over after 5 seconds...
Course math will over after 4 seconds...
Course math will over after 3 seconds...
Course math will over after 2 seconds...
Course math will over after 1 seconds...
Course math over ...
Please input your operation: vt

        Infomation for teacher lockey

            number : teacher1
            name : lockey
            age : 23
            gender: male
            course : math
                course number:course1
                course price :1200
                course time  :2017-10-01
            salary : 12300000

Please input your operation: vs

        Students attending math are as below

    number   name   age   gender   class
       studentmath1 halo      18     female        math
Please input your operation: q
User lockey exited!
Please input your operation(input "O" for operation menu list) : s
Please input your class: math
Please input username: halo
Please input password: student
For first logged in user, password should be changed!
Please input new password: redhat
Please confirm password: redhat

    Good afternoon!  [ halo ]

            menu lists

        (L)  : Learning
        (P) : Pay the fees
        (S) : Self info show
        (Q)  : quit

Please input your operation: l
halo start learning ...
halo keep learning ...
halo keep learning ...
halo keep learning ...
halo keep learning ...
halo keep learning ...
halo stop learning and go to date ...
Please input your operation: p
Fees paid off!
Please input your operation: s

        Infomation for student halo

            number : studentmath1
            name : halo
            age : 18
            gender : female
            feeState : 1200
            class : math
                course number:course1
                course price :1200
                course time  :2017-10-01

Please input your operation: q
User halo exited!
Please input your operation(input "O" for operation menu list) : q
System exited!
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值