Словарь, расположенный в других функциях ошибки при попытке доступа к ключу [Python]

#python #file #dictionary

#python #файл #словарь

Вопрос:

В настоящее время я пытаюсь использовать свой словарь grade_dict из моей функции file_input в моей функции file_output, но это не позволяет мне использовать ключи, чтобы я мог вставить то, что я хочу в свой output.txt досье. Это дает мне ошибку NameError для grade_category, потому что она не определена. Я довольно новичок в Python, поэтому я подозреваю, что это простое исправление, которое мне не хватает. Если бы я мог получить объяснение того, что я делаю неправильно, я был бы очень признателен и извлек из этого урок. (Извините за обилие кода и информации, которые могут не понадобиться. Я также новичок на этом сайте, и я хочу убедиться, что я предоставляю все, что потребуется)

Ошибка:

 Traceback (most recent call last):
  File "c:/Users/maste/Desktop/CS256/testing.py", line 87, in <module>
    file_output('output.txt', grade_dict)
  File "c:/Users/maste/Desktop/CS256/testing.py", line 79, in file_output
    output_file.write(line   ':'   grade_dict[grade_category][0]   'n')
NameError: name 'grade_category' is not defined
 

Код:

 def file_input(user_file):
    grade_dict = {}
    user_file = open(user_file, 'r')
    points_possible_list = []
    points_earned_list = []
    for line in user_file:
        grades = line.strip().split(', ')
        first, second, *rest = grades
        grade_category = first
        weight = second
        scores = rest
        grades = scores[0].split(',')
        for num in grades:
            points_possible = float(num.split('/')[1])
            points_possible_list.append(points_possible)
            points_earned = float(num.split('/')[0])
            points_earned_list.append(points_earned)
        grade_dict[grade_category] = [weight, points_earned_list, points_possible_list]
        points_possible_list = []
        points_earned_list = []
    user_file.close()
    return grade_dict


def average_score(points_earned, points_possible):
    """
    A function that calculates the average score of a single given grading category.
    The function will need to take in two lists as input (one for points_earned, and one for possible_points).
    Returns the floating-point average of the points earned in that specific category.
    """
    # The basic equation that takes the sum of the list of score_earned and the sum of the list of score_possible
    score = sum(points_earned) / sum(points_possible)
    return score

def grade_weighted(points_earned, points_possible, weight):
    """
    A function that calculates the weighted portion of the overall course grade for each of each category given.
    The function will need the list with points_earned, the list for possible_points, and the weight for each category is necessary.
    The function then multiplies the category average times the weight of that category.
    """
    # Makes all the previous scores for each of the categories weighted with this equation
    weighted_score = average_score(points_earned, points_possible) * weight  
    return weighted_score

def letter_grade(grade_total):
    """
    A function that takes in a number between 0 and 1 and returns the appropriate letter grade according to the United States Grading System.
    """
    # Create an if-else-elif statement regarding the grading system mentioned before
    if grade_total >= .93:
        grade_total = 'A'
    elif grade_total >= .90:
        grade_total = 'A-'
    elif grade_total >= .87:
        grade_total = 'B '
    elif grade_total >= .83:
        grade_total = 'B'
    elif grade_total >= .80:
        grade_total = 'B-'
    elif grade_total >= .77:
        grade_total = 'C '
    elif grade_total >= .73:
        grade_total = 'C'
    elif grade_total >= .70:
        grade_total = 'C-'
    elif grade_total >= .67:
        grade_total = 'D '
    elif grade_total >= .60:
        grade_total = 'D'
    elif grade_total >= .0:
        grade_total = 'F'
    return grade_total 


def file_output(file_name, grade_dict):
    output_file = open(file_name, 'w')
    # grade_weighted(grade_dict[points_earned], points_possible, weight)
    for line in grade_dict:
        output_file.write(line   ':'   grade_dict[grade_category][0]   'n')
    pass


if __name__ == "__main__":
    # user_file = file_input(str(input('Enter filename (example: text.txt): ')))
    grade_dict = file_input('grade_input.txt')
    #grade_dict = file_input('coding_grades.txt')
    file_output('output.txt', grade_dict)
 

grade_input.txt содержимое файла:

 Homework, 10%, 40/40,10/40,30/40,4/5,18/40,40/40,76/80,10/10
Quizzes, 10%, 10/10,10/10,8/10,9/10,0/10,10/10,6/10 
Tests, 35%, 89/100,97/100
Projects, 30%, 56/60,60/60
Final, 15%, 495/550
 

Комментарии:

1. Словарь не выдает ошибку, вы пытаетесь использовать переменную, которая не определена в этой области, grade_category , следовательно NameError . Вы имели в виду grade_dict[line][0] ?

2. О, да! Опять же, я новичок в программировании, поэтому это было что-то очень простое. Я действительно очень ценю помощь! Теперь это имеет такой смысл, что я перечитал его. Большое вам спасибо!