Home > Net >  Is there a option to add a subject to the mark?
Is there a option to add a subject to the mark?

Time:10-14

I build a program that containing the id of a student and the marks list in each subject where different students have taken a different number of subjects.

I am trying to add the name of the subject near to his mark but I can't find any solution for it.

This is the following code that I wrote:

def GetStudentDataFromTeacher ():
    D ={}
    while True:
        StudentId = input ("Enter The Student ID:")
        StudentMarks = input ("Enter The Student Each Marks:")
        MoreStudents = input ('If you dont have more student type "no":')
        if StudentId in D:
            print (StudentId, "**You Already Type this student")
        else:
            D[StudentId] = StudentMarks.split (",")
        if MoreStudents.lower() == "no":
            return D

Thank you!!

CodePudding user response:

You can ask the user to enter the grades in a specific format and then convert this string into a dictionary where the key will be the subject and the value is the grade.

For example, you can ask the user to enter in the following format: <subject1>--<grade1>,<subject2>--<grade2>.

The code will be:

def get_students_data():
    students_grades = {}
    while True:
        student_id = input("Enter The Student ID:")
        grades = input("Enter the student grades in the following format <subject1>--<grade1>,<subject2>--<grade2>:")
        more_students = input('If you dont have more student type "no":')
        if student_id in students_grades:
            print(student_id, "**You Already Type this student")
        else:
            students_grades[student_id] = {subject_grade.split("--")[0]: subject_grade.split("--")[1] for subject_grade
                                           in grades.split(",")}
        if more_students.lower() == "no":
            return students_grades

print(get_students_data())

The output will be:

# Enter The Student ID: 1
# Enter the student grades in the following format <subject1>--<grade1>,<subject2>--<grade2>:: math--90,history--70
# If you dont have more student type "no": no
{'1': {'math': '90', 'history': '70'}}

There might be better ways to achieve this behaviour (you can create a json file with all the grades data in a much more structured way and then ask the user for its path and parse it) but the above snippet will work if you want to stick to your solution.

  • Related