Я работаю над заданием из python, которое доставляет мне немало хлопот.
Я создал класс, который принимает данные для учеников в классе.
Мне нужно сделать следующее:
- Посмотрите и отобразите только gpa от конкретного ученика.
- Добавление новых учеников в класс.
- Изменить средний балл студента.
- Изменить ожидаемую оценку ученика.
- Распечатать данные всех студентов в табличном формате.
- Выйдите из программы и сохраните все созданные файлы.
Пока мне удалось заблокировать данные печати. Сохранение и выход работает как задумано.
Я сталкиваюсь с ошибками в пунктах меню 1 - 4 с различными ошибками. Это первый раз, когда я действительно был озадачен и нуждался в помощи специалиста. Книга не так уж велика.
Например, функция add_student вернула две отдельные ошибки:
при настройке entry = student.Student(name, studentid, gpa, expgrade, status)
Я получаю ошибку NameError: name student is not defined
Если я попытаюсь Student(name, studentid, gpa, expgrade, status)
Я получаю ошибку TypeError: argument of type 'Student' is not iterable.
class Student:
def __init__(self, name, studentid, gpa, expgrade, status):
self.__name = name
self.__studentid = studentid
self.__gpa = gpa
self.__expgrade = expgrade
self.__status = status
def set_name(self, name):
self.__name = name
def set_studentid(self, studentid):
self.__studentid = studentid
def set_gpa(self, gpa):
self.__gpa = gpa
def set_expgrade(self, expgrade):
self.__expgrade = expgrade
def set_status(self, status):
self.__status
def get_name(self):
return self.__name
def get_studentid(self):
return self.__studentid
def get_gpa(self):
return self.__gpa
def get_expgrade(self):
return self.__expgrade
def get_status(self):
return self.__status
def __str__(self):
return 'Name:' + self.__name + \
'\nId Number:' + self.__studentid + \
'\nGPA: ' + self.__gpa + \
'\nExpected Grade: ' + self.__expgrade + \
'\nEnrollment Status: ' + self.__status
import pickle
LOOK_UP = 1
ADD_STUDENT = 2
CHANGE_GPA = 3
CHANGE_EXPGRADE = 4
PRINT_DATA = 5
QUIT = 6
FILENAME = 'students.dat'
def main():
st_1 = Student('Ryan Galloway', '2223344', '3.9', 'A', 'FT')
st_2 = Student('Renee Polanco', '2345432', '4.0', 'A', 'PT')
st_3 = Student('Jane Doe', '3245655', '2.2', 'C', 'PT')
st_4 = Student('John Doe', '1234567', '3.0', 'B', 'FT')
st_5 = Student('Marvin Martian', '0987568', '1.8', 'F', 'PT')
output_file = open(FILENAME, 'wb')
pickle.dump(st_1, output_file)
pickle.dump(st_2, output_file)
pickle.dump(st_3, output_file)
pickle.dump(st_4, output_file)
pickle.dump(st_5, output_file)
output_file.close()
students = load_students()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == LOOK_UP:
look_up(students)
elif choice == ADD_STUDENT:
add_student(students)
elif choice == CHANGE_GPA:
change_gpa(students)
elif choice == CHANGE_EXPGRADE:
change_expgrade(students)
elif choice == PRINT_DATA:
print_data(students)
elif choice == QUIT:
save(students)
def load_students():
try:
input_file = open(FILENAME, 'rb')
student_dct = pickle.load(input_file)
input_file.close
except IOError:
student_dct = {}
return student_dct
def get_menu_choice():
print()
print('Menu')
print('--------------------------')
print("1. Look up and display a student's GPA")
print("2. Add a new student")
print("3. Change the GPA of a student")
print("4. Change the expected grade of a student")
print("5. Print all student data")
print("6. Quit the program and save information")
print()
try:
choice = int(input('Enter your choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
except ValueError:
print('That is not a valid input. Please restart the program.')
def look_up(students):
name = input('Enter the student name: ')
if name in students:
print(students.gpa)
else:
print('That name does not exist.')
def add_student(students):
name = input('Name: ')
studentid = input('Student ID number: ')
gpa = input('GPA: ')
expgrade = input('Expected Grade: ')
status = input('Full Time (FT) or Part Time(PT): ')
entry = student.Student(name, studentid, gpa, expgrade, status)
if name not in students:
student[name] = entry
else:
print('That student is already logged.')
def change_gpa(students):
name = input('Enter a student name: ')
if name in students:
gpa = input('Enter the new GPA: ')
entry = Student(name, studentid, gpa, expgrade, status)
students[name] = entry
print('Information updated.')
else:
print('That name is not found.')
def change_expgrade(students):
name = input('Enter a name: ')
if name in students:
expgrade = input('Enter the new expected grade for the student: ')
entry = Student(name, studentid, gpa, expgrade, status)
students[name] = entry
else:
print('That name was not found.')
def print_data(students):
end_of_file = False
input_file = open(FILENAME, 'rb')
try:
while not end_of_file:
student_data = pickle.load(input_file)
display_data(student_data)
except EOFError:
end_of_file = True
input_file.close()
def save(students):
output_file = open(FILENAME, 'wb')
pickle.dump(students, output_file)
output_file.close()
def display_data(student_data):
print('Name: ', student_data.get_name())
print('Student ID: ' , student_data.get_studentid())
print('GPA: ', student_data.get_gpa())
print('Expected Grade: ', student_data.get_expgrade())
print('Enrollment Status: ', student_data.get_status())
print()
main()