Beispiel #1
0
def dummy_data():
    student_1 = Student('Student 1', 'Economics')
    student_2 = Student('Student 2', 'Sports')
    working_student_1 = Working_student('Working Student 1', 'Web Dev',
                                        'Full stack developer', 25000)
    working_student_2 = Working_student('Working Student 2', 'Web Dev',
                                        'Junior Python Developer', 17000)
    student_1.add_grade(80)
    student_1.add_grade(70)
    student_1.add_grade(86)
    student_2.add_grade(90)
    student_2.add_grade(93)
    student_2.add_grade(91)
    working_student_1.add_grade(65)
    working_student_1.add_grade(70)

    students.extend(
        [student_1, student_2, working_student_1, working_student_2])

    teacher_1 = Teacher('Corey Schaufer', 'Python')
    teacher_2 = Teacher('Pretty Printed', 'Django')
    teacher_3 = Teacher('The Net Ninja', 'Javascript')

    teachers.extend([teacher_1, teacher_2, teacher_3])

    print('Dummy data created sucessfully! \n')
Beispiel #2
0
def test_classes():
    """
    Добавить модуль classes и реализовать класс classes.Student, который в конструкторе принимаем полное имя студента
    (full_name) и название курса, опционально (course_name), в инициалзаторе студенту присваивается атрибут
    course_num = 1. Дополнительно надо реализовать exception classes.StudentCourseError  Класс имеет 3 метода:
    - next_course(), который увиличивает текущий курс на один. Если в конструкторое не было передан курс в конструкторе,
      "бросает" ошибку StudentCourseError('Not have course'). Если курс равен 3 "бросает" ошибку
      StudentCourseError('Student have degree')
    - change_course(course_name), меняет название курса и сбрасывает course_num в 1
    - get_diploma(), возвращает строчку в которой через запятую full_name и course_name, если курс меньше 3 "бросает"
      ошибку StudentCourseError('Student not have degree')
    два числа, и возращает их разность если второе меньше первого, в противном случае "бросает" ValueError,
    с текстом "Max error"
    https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions
    https://docs.python.org/3/tutorial/classes.html
    :return:
    """
    # Case 1
    lucy_smith = Student('Lucy Smith')
    assert lucy_smith.full_name == 'Lucy Smith'
    assert lucy_smith.course_name is None
    assert lucy_smith.course_num == 1

    with pytest.raises(StudentCourseError, match=r'Not have course'):
        lucy_smith.next_course()

    lucy_smith.change_course('Python')
    assert lucy_smith.course_name == 'Python'

    lucy_smith.next_course()
    assert lucy_smith.course_num == 2

    with pytest.raises(StudentCourseError, match=r'Student not have degree'):
        lucy_smith.get_diploma()

    lucy_smith.next_course()
    assert lucy_smith.course_num == 3
    with pytest.raises(StudentCourseError, match=r'Student have degree'):
        lucy_smith.next_course()

    assert lucy_smith.get_diploma() == 'Lucy Smith,Python'

    # Case 2
    joe_smith = Student('Joe Smith', 'NodeJS')
    assert joe_smith.full_name == 'Joe Smith'
    assert joe_smith.course_name == 'NodeJS'
    assert joe_smith.course_num == 1

    joe_smith.next_course()
    assert joe_smith.course_num == 2
    joe_smith.change_course('Python')
    assert lucy_smith.course_name == 'Python'
    assert joe_smith.course_num == 1
Beispiel #3
0
def student_page():  # student sign in page
    if request.method == "POST":
        user = Student("", "", "", "", "")
        user.email = request.form['email']
        user.password = request.form['password']
        result = db.get_student(user.email)

        if result:
            password2 = result['student_password']
            if hasher.verify(user.password, password2):
                session['logged_in'] = True
                session['s-email'] = user.email
                session['s-name'] = result['student_name']
                session['s-surname'] = result['student_surname']
                session['s-id'] = result['student_id']
                flash('You are now logged in', 'success')  #??
                return redirect(
                    url_for('student_main_page', name=result['student_name']))
            else:
                error = " Wrong password!"
                return render_template('student_sign.html', error=error)

        else:
            error = " Email not found!"
            return render_template('student_sign.html', error=error)

    return render_template('student_sign.html')
Beispiel #4
0
 def ld_students(cls, file_name):
     """Загрузка данных об учащихся"""
     with codecs.open(file_name, encoding='utf-8') as fl:
         data = fl.readlines()
     for student in data:
         full_name, birthday = student.strip().split(';')
         student = Student(full_name, birthday)
         cls.lst_students.append(student)
    def generate_students(self):
        """
        Generate students, giving a level of ability in each subject
        """
        student = Student()
        self.students = student.generate_students()

        print('\033[44m' + '***********STUDENTS*************' + '\033[0m')
        pprint(self.students)
Beispiel #6
0
 def load_students(self):
     students = []
     lines = default_read_and_filter_csv('students.txt')
     index = 0
     for line in lines:
         students.append(
             Student(index, line['name'].strip(),
                     line['prioritized_list'].strip()))
         index += 1
     return students
Beispiel #7
0
def sudents_page():
    if request.method == 'POST':
        new_student_id = request.form.get('student_id', "")
        new_student_name= request.form.get('name', '')
        new_student_last_name= request.form.get('last-name', '')

        new_student = Student(name=new_student_name, student_id = new_student_id)
        students.append(new_student)

        return redirect(url_for('student_page'))
    return render_template('index.html', students=students)
Beispiel #8
0
    def test_assign_quiz_to_student(self):
        self.student = Student(name='ramadan')
        self.quiz1 = Quiz()
        self.quiz2 = Quiz()

        self.assertEqual([], self.student.quizzes)

        Teacher.assign_quiz_to_student(self.student, self.quiz1)
        self.assertEqual([self.quiz1], self.student.quizzes)

        Teacher.assign_quiz_to_student(self.student, self.quiz2)
        self.assertEqual([self.quiz1, self.quiz2], self.student.quizzes)
Beispiel #9
0
 def load_students(self):
     students = []
     with self.connection.cursor() as cur:
         cur.execute(
             "select concat(ucase(surname), ' ', givenname) as name, level, prioritized_list from students"
         )
         index = 0
         for row in cur:
             student = Student(index, row['name'].strip(),
                               row['prioritized_list'].strip())
             student.level = row['level'].strip()
             students.append(student)
             index += 1
     return students
Beispiel #10
0
    def download_list(self):
        """
        Devuelve una lista de Student con todos los estudiantes en el servidor
        """

        students = []
        #############
        estudiantes = requests.get(
            "http://assistance-py.herokuapp.com/students")
        for i in estudiantes.json()["students"]:
            students.append(
                Student(i["name"], i["username"], i["assistance"], i["id"]))

        return students
Beispiel #11
0
    def download_list(self):
        """
        Devuelve una lista de Student con todos los estudiantes en el servidor
        """

        # Solucion ------------------------------------------------------------
        students = []
        request = requests.get(url="{}/students".format(self.url))
        for dic in request.json()['students']:
            students.append(
                Student(id=dic['id'],
                        name=dic['name'],
                        username=dic['username'],
                        assistance=dic['assistance']))
        # -----------------------------------------------------------------------

        return students
Beispiel #12
0
def initial_frame(img):
    """initializes student object

    Args:
       img: first image in directory

    Returns:
        list of student objects

    """
    student_list = []
    faces = find_faces(img)
    for i in range(len(faces)):
        student_list.append(Student(faces[i], str(i)))

    for student in student_list:
        get_pose_direction(student, img)
        get_angle(student)
    return student_list
Beispiel #13
0
def signUp():
    if request.method == "POST":
        form_name = request.form["fname"]
        form_surname = request.form["lname"]
        form_id = request.form["ownid"]
        form_email = request.form["Email"]
        form_password = hasher.hash(request.form["password"])
        form_person = request.form["person"]
        db = current_app.config["db"]
        if request.form["password"] != request.form[
                "confirm_password"]:  #for error
            password_error = "Passwords not matching! Try Again"
            return render_template('signup.html',
                                   password_error=password_error)

        if db.check_exists_student_id(form_id) or db.check_exists_teacher_id(
                form_id):  #for error
            error = "The ID exists! Try Again"
            return render_template('signup.html', error=error)

        if db.check_exists_student_email(
                form_email) or db.check_exists_teacher_email(
                    form_email):  #for error
            error = "The email has already used!"
            return render_template('signup.html', error=error)

        if form_person == "teacher":
            teacher = Teacher(form_id, form_name, form_surname, form_email,
                              form_password)
            teacher_key = db.add_teacher(teacher)
            return redirect(url_for("successful", teacher_key=teacher_key))

        elif form_person == "student":
            student = Student(form_id, form_name, form_surname, form_email,
                              form_password)
            student_key = db.add_student(student)
            return redirect(url_for("successful", student_key=student_key))
        else:
            return "person is not chosen!"
    else:
        return render_template('signup.html')
Beispiel #14
0
def create_student():
    """
    Function to create a student
    """
    name = input('Name of new student: \n').title()
    course = input('Which course is taking: \n').title()
    working = input('Is this student working? (y/n) \n').lower()

    if working == 'y':
        job = input("What's his job: \n")
        try:
            pay = int(input("Yearly Payment: \n"))
            working_st = Working_student(name, course, job, pay)
            students.append(working_st)
            return print(f'\nStudent added!')
        except ValueError:
            return print(value_error_message)

    new_student = Student(name, course)
    students.append(new_student)
    return print(f'\nStudent added!')
Beispiel #15
0
def find_new_students(student_list, next_frame, index):
    """looks for new students and appends them to student_list

    Args:
       student_list: list of objects
       next_frame: next image
       index: the index of the frame

    Returns:
        student_list

    """
    faces = find_faces(next_frame)
    for face in faces:

        found = False
        top_left = face['keypoints']['left_eye']
        bottom_right = face['keypoints']['mouth_right']
        box = utils.extend_box(top_left, bottom_right, 50)

        for student in student_list:
            test_point = student.face_points['nose']

            # img = next_frame.copy()
            # cv2.circle(img, test_point,1,(0,0,255),2)
            # cv2.rectangle(img, box[0], box[1], (255,255,0),1)
            # utils.show_image(img)

            if utils.point_in_box(box, test_point):
                found = True
                break

        if not found:
            max_name = max([int(x.name) + 1 for x in student_list])
            attention_list = [random.randint(1, 359) for i in range(index + 1)]
            student_list.append(Student(face, max_name))
            student_list[-1].attention_angle_list = attention_list
Beispiel #16
0
from classes import Student

student = Student(input("How many questions?"), input("What difficultly do you want?"))
if "easy" in student.get_level():
    student.easy_test()
elif "medium" in student.get_level():
    student.medium_test()
elif "hard" in student.get_level():
    student.hard_test()
def get_mentees(sheetname="CovEd student form (New)"):
    mentees = []

    #variables containing the headings of columns in google forms.
    name_head = 'Full Name:'
    email_head = 'Email Address'
    grade_head = "What is your age group? (Repeaters in any particular stream please select the 11-12 option in the corresponding stream)"
    foreignuniv_head = "Some mentors have experience with College Applications for foreign universities (like essays and other stuff). Do you require some help with that? (Please select yes only if you are really considering applying to a foreign university soon)"
    subjects_head = "What subjects do you specifically need help with?"
    extracurricular_head = "Would you be interested in receiving extra curricular support from your mentor (Answer the next question only if your response to this question is Yes):"
    feedback_head = "If you are filling this form for the second time and have already been assigned a mentor, are you happy with the mentor assigned to you?"
    emotype_head = "Please select all the box pertaining to the area that you need support with with (once again please be considerate and only select something if you genuinely need help with it):"
    gender_head = "What is your gender? (Note that we are providing this facility only in the case of students requiring emotional support as some issues can be sensitive. For general academic help this option will not be taken into account)"
    assigned_mentor_head = "Mentor"

    #fetch data from sheet
    records, mentee_sheet = get_data_from_sheet(sheetname)

    row_no = 1

    for row in records:
        row_no += 1
        #For some cases, the values do not match what is given in the dictionary.
        try:

            if row[assigned_mentor_head].replace(' ', '') == '':
                assigned_mentor = None
            else:
                assigned_mentor = row[assigned_mentor_head]

            feedback = classes_model.feedback[row[feedback_head]]

            ## Appending only the unassigned students to save time
            if assigned_mentor != None and feedback != 2:
                continue

            if feedback == 1 or feedback == 4:
                continue

            name = row[name_head]
            email = row[email_head]
            classes = classes_model.class_ids[row[grade_head]]
            foreignuniv = classes_model.bool_dict[
                row[foreignuniv_head] if row[foreignuniv_head] != '' else
                'No']  #some entries were blank in forms.
            subjects = row[subjects_head].split(
                ",")  #Assumed list in assignmentor
            extracurricular = classes_model.bool_dict[
                row[extracurricular_head]]
            if extracurricular:
                emotype = [
                    classes_model.emotype[y.strip()]
                    for y in row[emotype_head].split(",")
                ]  #split- assignmentor assumes list. strip- google forms appends whitespaces which can be difficult to keep in account
                if 0 not in emotype:
                    emotype.append(0)
            else:
                emotype = [0]

            # print("Student", extracurricular, emotype)

            try:  #Made like this because some people have not filled gender even after saying Yes to support
                gender = classes_model.gender[row[gender_head]]
            except:
                gender = None

            #Initialise mentee object
            student_object = Student(name,
                                     email,
                                     classes,
                                     foreignuniv,
                                     subjects,
                                     extracurricular,
                                     emotype=emotype,
                                     gender=gender,
                                     feedback_type=feedback,
                                     assigned_mentor=assigned_mentor,
                                     row_no=row_no)
            mentees.append(student_object)

        except:
            print("Some Error Occured : Student")
            print(row[name_head], row[email_head])
            print("\n#############################################\n")
            continue

    return mentees, mentee_sheet
Beispiel #18
0
def students_subroutine(student_list):
    """
    Subroutine for working with student list.
    """
    while True:
        pretty.print_bar(PROGRAM_WIDTH)
        print(
            "What would you like to do? (type either option number or [keyword])"
        )
        pretty.print_options("[View] students", "[Add] student",
                             "[Remove] student", "[Update] student info",
                             "[Return]")
        inp = input().lower()

        if inp == "1" or inp == "view":
            start = end = None
            start_inp = input(
                "First letter to start at? (Leave blank to start at beginning)\n"
            )
            if start_inp and valid.is_letter(start_inp):
                start = start_inp
            else:
                start = "a"
            end_inp = input(
                "First letter to end at? (Leave blank to go until end)\n")
            if end_inp and valid.is_letter(end_inp):
                end = end_inp
            else:
                end = "z"
            print()
            pretty.print_bar(PROGRAM_WIDTH)
            try:
                student_list.print_table(start, end)
            except ValueError as e:
                print(e)
            print()
            input("Press enter to return.")

        elif inp == "2" or inp == "add":
            # Add new student to student list.
            # Basic flow: ask for all arguments in a try/except block listening
            # for KeyboardInterrupts. If any are raised, exit add subroutine
            # and continue looping. Otherwise, create a new Student with given
            # parameters and add to students list. Report success.
            print("Press CTRL+C at any time to cancel.")
            args = []
            try:
                # Got all of the arguments at once in a list and then just expanded them
                # into the parameters for new Student. Less readable, but more compact.
                args.append(input("First name?\n").strip(' '))
                args.append(input("Last name?\n").strip(' '))
                args.append(input("Phone number?\n"))
                args.append(input("Email address?\n"))
                args.append(input("Class or subject?\n"))
                args.append(input("Notes?\n"))
            except KeyboardInterrupt:
                pass
            else:
                pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM)
                student_list.add(Student(*args))
                print("Student {0} added successfully.".format(args[0] + " " +
                                                               args[1]))
                save(student_list, transaction_record=None)

        elif inp == "3" or inp == "remove":
            # Remove student by name from student list.
            # Basic flow: Ask for name of student to remove in try/except block
            # listening for KeyboardInterrupts. If any are raised, exit remove
            # subroutine and continue looping. Else use StudentList method to
            # remove student with given name and report success or failure
            # (returned by method).
            print("Press CTRL+C at any time to cancel.")
            try:
                name = input("Full name of student to remove?\n")
            except KeyboardInterrupt:
                pass
            else:
                pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM)
                removed = student_list.remove(name)
                if removed:
                    print("Student {0} removed successfully.".format(name))
                    save(student_list, transaction_record=None)
                else:
                    print("Student {0} not found (check spelling?).".format(
                        name))

        elif inp == "4" or inp == "update":
            # Update student info in student list.
            # Basic flow: Ask for name of student to update in try/except block
            # listening for KeyboardInterrupts. If any are raised, exit remove
            # subroutine and continue looping. Else use StudentList method to
            # update student with given name. Ask for field and new value to update
            # to. Report success or failure (returned by method). Student field
            # updates have no type checking for values.
            print("Press CTRL+C at any time to cancel.")
            try:
                name = input("Full name of student to update?\n")
                print("Field to update? (type by [keyword])")
                pretty.print_options("[First] name", "[Last] name",
                                     "[Phone] number", "[Email] address",
                                     "[Subject] or class", "[Notes]")
                field = input().lower()
                newval = input("New value of field?\n")
            except KeyboardInterrupt:
                pass
            else:
                pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM)
                #  This works because update method returns True or False for successful update or not.
                updated = student_list.update(name, field, newval)
                if updated:
                    #  A little magic in format to make update to field "first" or "last" show as "first name" or "last name."
                    print(
                        "Student {0} {1} successfully updated to {2}.".format(
                            name, field + ("name" if field == "first"
                                           or name == "last" else ""), newval))
                    save(student_list, transaction_record=None)
                else:
                    print(
                        "Student {0} or field {1} not found (check spelling?)."
                        .format(name, field))

        elif inp == "5" or inp == "return":
            # Finishes method and returns to place in main() stack loop.
            return
        else:
            pass
Beispiel #19
0
    "Lecturer": [["lecture", "phone number", "profession", "password"]],
    "Coordinator": [["coordinator", "phone number", "password"]]
}

"Database of questions using dictionary"


def add_user(obj: Student or Lecturer or Coordinator):
    if type(obj) == Student:
        user_list["Student"].append((obj.get_name(), obj.get_password()))
    elif type(obj) == Lecturer:
        user_list.update({
            "Lecturer": [obj.name, obj.phone_number, obj.topic, obj.password]
        })
    else:
        user_list.update(
            {"Coordinator": [obj.name, obj.phoneNumber, obj.password]})


def del_user(string: str):
    for lec in user_list["Lecturer"]:
        if lec == user_list["Lecturer"][0]:
            user_list["Lecturer"].pop(0)


stu = Student("eliran", "123")
add_user(stu)
print(user_list["Student"])
del_user("full name")
print(user_list["Lecturer"])
Beispiel #20
0
from classes import HighSchoolStudent, Student

jess = Student("Jessica", "Monteiro")
print(jess)
Beispiel #21
0
 def import_students_from_json(self) -> typing.Iterable[Student]:
     with open(self.students_path, 'r') as students_file:
         for student in json.load(students_file):
             yield Student(**student)
def student():
    return Student("bruce")
Beispiel #23
0
 def setUp(self):
     self.student = Student(name='ramadan')
     self.quiz = Quiz()
Beispiel #24
0
from functions import *
from classes import Employee, Student

a()
b()
c()

e1 = Employee(101, "Payal", 22, 1000000, "CEO")
e1.display()

s1 = Student(11, "ranu", 12)
s1.display()
Beispiel #25
0
Методы:
    create_homework - текст задания и количество дней на это задание,
    возвращает экземпляр Homework
    Обратите внимание, что для работы этого метода не требуется сам объект.

PEP8 соблюдать строго, проверку делаю автотестами и просмотром кода.
Всем перечисленным выше атрибутам и методам классов сохранить названия.
К названием остальных переменных, классов и тд. подходить ответственно -
давать логичные подходящие имена.
"""

from classes import Student, Teacher

if __name__ == '__main__':
    teacher = Teacher('Daniil', 'Shadrin')
    student = Student('Roman', 'Petrov')
    teacher.last_name  # Shadrin
    student.first_name  # Roman

    expired_homework = teacher.create_homework('Learn functions', 0)
    expired_homework.created  # Example: 2019-05-26 16:44:30.688762
    expired_homework.deadline  # 0:00:00
    expired_homework.text  # 'Learn functions'

    # create function from method and use it
    create_homework_too = teacher.create_homework
    oop_homework = create_homework_too('create 2 simple classes', 5)
    oop_homework.deadline  # 5 days, 0:00:00

    student.do_homework(oop_homework)
    student.do_homework(expired_homework)  # You are late
Beispiel #26
0
def self_vs_instructor_repeater(repeaters, course):
    self_paced_run = course.self_paced_run
    index_of_self_paced = course.semester_names.index(self_paced_run)
    test_in = Cohort()
    test_out = Cohort()
    test = Cohort()
    control = Cohort()

    retook_dic = defaultdict(list)

    for userid in repeaters.get_keys():
        student = repeaters.get(userid)
        if repeaters.get_num_semesters(userid) >= 2:
            if student.is_in_semester(self_paced_run):
                # add to test_in
                entity = student.get(self_paced_run)
                new_student = Student(student.userid)
                new_student.add(self_paced_run, entity)
                test_in.add(userid, new_student)
                # add to test_out
                new_student = student.deep_copy()
                # print(new_student.get_keys())
                test.add(userid, new_student)
                new_student.delete(self_paced_run)
                test_out.add(userid, new_student)
            else:
                control.add(userid, student.deep_copy())

            for sem_name in student.get_keys():
                if course.is_first_or_last_semester(sem_name):
                    continue
                retook_dic[sem_name].append(
                    0 if sem_name ==
                    student.get_last_semester(course.semester_names) else 1)

    print()
    print('REPEATERS WHO DIDNT TAKE SELF-PACED:')
    print('completion % overall: ', control.get_completion_rate())
    print('average grade overall: ', control.get_average('overall', True))
    print('average grade overall: ', control.get_average('overall_1', True))
    print('ever completed:', control.get_ever_completed_rate())

    print()
    print('REPEATERS IN SELF-PACED DURING SELF-PACED SEM:')
    print('completion % overall: ', test_in.get_completion_rate())
    print('average grade overall: ', test_in.get_average('overall', True))
    print('average grade overall: ', test_in.get_average('overall_1', True))
    print('ever completed:', test_in.get_ever_completed_rate())

    print()
    print('REPEATERS IN SELF-PACED DURING INSTRUCTOR-LED SEM:')
    print('completion % overall: ', test_out.get_completion_rate())
    print('average grade overall: ', test_out.get_average('overall', True))
    print('average grade overall: ', test_out.get_average('overall_1', True))
    print('ever completed:', test_out.get_ever_completed_rate())

    print()
    print('RETAKING COURSE')
    ls = []
    for key in retook_dic:
        if key == self_paced_run:
            print("self paced", statistics.mean(retook_dic[key]))
        else:
            ls.append(statistics.mean(retook_dic[key]))
    print("instructor ", statistics.mean(ls))

    x = [0, 1, 2, 4, 5]
    x_labels = [
        'ever', 'self\n\n\nGroup A', 'instuctor', 'ever', '\n\n\nGroup B',
        'instuctor'
    ]
    y = [
        test.get_ever_completed_rate(),
        test_in.get_completion_rate(),
        test_out.get_completion_rate(),
        control.get_ever_completed_rate(),
        control.get_completion_rate()
    ]
    plt.bar(x, y, align='center')
    plt.ylabel('% of learners who complete', fontsize=12)
    plt.xticks([0, 1, 2, 4, 4.5, 5], x_labels, fontsize=12)
    plt.savefig("anything" + ("1x" if course.is_1x else "2x") + ".png",
                bbox_inches='tight')
    plt.clf()
Beispiel #27
0
from classes import Teacher, Student, Course

compsci = Course("Computer Science 101", "CS101")
maria = Student("Maria", "Martinez")
joe = Student("Joe", "Smith")
ashven = Student("Ashven", "Matthew")

imani = Teacher("Imani", "Matthews")

compsci.add([maria, joe, ashven])
compsci.set_teacher(imani)

print(compsci.teacher, compsci.students)

joe.addgrade(compsci, 80)
joe.addgrade(compsci, 89)
joe.addgrade(compsci, 100)

print()
print("GPA for {} is {:.2f}.".format(joe, joe.gpa_for(compsci)))
Beispiel #28
0
from classes import Student

student1 = Student("Vipin", "B.tech", 3.0, False)
student2 = Student("Savi", "MBA", 5.0, True)
print(student1.name + " is honor:" + str(student1.on_honor_roll()))
print(student2.name + " is honor:" + str(student2.on_honor_roll()))


Beispiel #29
0
# attribute "courses_grades".
# Create the method **average_grade**. Calculate and return the students
# average grade. Ignore grades with "-" in the calculation.
#
# Create a new instance of the class Student. Initiate it with the name
# `Zimba` and ssn `516518-3442`.
# Use the add_course_grade method to add the following courses, `htmlphp`
# with grade `2`, `design` with grade `-` and `linux` with grade `5`.
#
#
# Answer with the Student object's "average_grade" method.
#
# Write your code below and put the answer into the variable ANSWER.
#

student = Student("Zimba", "516518-3442")
student.add_course_grade("html", 2)
student.add_course_grade("design", "-")
student.add_course_grade("linux", 5)

ANSWER = student.average_grade()

# I will now test your answer - change false to true to get a hint.
dbwebb.assert_equal("1.4", ANSWER, False)

# """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Exercise 1.5 (1 points)
#
# In Teacher, create the *classmethod* **from_json**. This shall take one
# argument, `filename`.
# The *filename* is a json -file that contains data to create and return a
Beispiel #30
0
#Create instances of cohorts
cohort_37 = Cohort("Cohort 37")
cohort_38 = Cohort("Cohort 38")
cohort_39 = Cohort("Cohort 39")

#Create Instances of instructors
instructor_andy = Instructor("Andy", "Collins", "*****@*****.**", cohort_38,
                             "JavaScript")
instructor_jisie = Instructor("Jisie", "David", "*****@*****.**", cohort_38,
                              "Python")
instructor_steve = Instructor("Steve", "Brownlee", "*****@*****.**",
                              cohort_37, "JavaScript")

#Create instances of students
student_matt = Student("Matt", "Crook", "*****@*****.**", cohort_38)
student_mike = Student("Mike", "Pence", "*****@*****.**", cohort_38)
student_kub = Student("Kub", "Docker", "*****@*****.**", cohort_38)
student_sara = Student("Sara", "Vue", "*****@*****.**", cohort_37)
student_bruce = Student("Bruce", "Brown", "*****@*****.**", cohort_39)

# Have the instructors assign an exercise to a student
instructor_andy.add_exercise(student_matt, list_exercise)
instructor_jisie.add_exercise(student_bruce, interface_exercise)
instructor_steve.add_exercise(student_kub, function_currying)
instructor_andy.add_exercise(student_mike, multiple_inheritance_exercise)
instructor_jisie.add_exercise(student_sara, classes_exercise)
instructor_andy.add_exercise(student_matt, classes_exercise)

# Create a list of students. Add all of the student instances to it.
students = list()