首页 > 解决方案 > 为什么我的 python 程序没有给出正确的文件输出?

问题描述

您好,我的作业有问题...我不断收到一个错误,我将在我的程序之后发布。

我的程序

def create():

    myGrades_file = open('grades.txt','w')

    while True:

        my_courses = input("Enter course name or Enter to quit: ")

        if my_courses == '':

            print("File was created and closed")

            break

        my_grades = int(input("Enter grade (integer) achieved: "))

        string = my_courses+','+" "+str(my_grades)+'\n'

        myGrades_file.write(string)

    myGrades_file.close()

    return True

def retrieve():

    print("\nHere are your grades:")

    grades_total = 0

    count = 0

    gpa=0    

    myGrades_file = open('grades.txt','r')

    for line in myGrades_file:

        mycourses, grades = line.strip().split(',')

        grades_total+=int(grades)

        if(int(grades)>=90):

            gpa+=4.0

        elif(int(grades)>=80):

            gpa+=3.0

        elif(int(grades)>=70):

            gpa+=2.0

        elif(int(grades)>=60):

            gpa+=1.0

        else:

            gpa+=0.0

        count+=1

        gpa_total = gpa/count

        print("{} score is{}".format(mycourses,grades))

    average = grades_total/count

    print("Average grade among your courses is {:.2f}".format(average),"Your GPA is {:.2f}".format(gpa_total))

    return average

def main():

    create()

    average = retrieve()

main()

由于某种原因,我无法弄清楚我做错了什么!

错误

Test 2 Expected data: ['CGS1070', '98'] Data in file: ['CGS1070, 98']Test 2 FailedE
======================================================================
ERROR: test_2_io_case_2 (__main__.programTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
AssertionError: Lists differ: ['CGS1070, 98'] != ['CGS1070', '98']

First differing element 0:
'CGS1070, 98'
'CGS1070'

Second list contains 1 additional elements.
First extra element 1:
'98'

- ['CGS1070, 98']
+ ['CGS1070', '98']
?          +  +


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
ValueError: Contents of file != Expected

标签: python

解决方案


推荐阅读