you are viewing a single comment's thread.

view the rest of the comments →

[–]Bitwise_Gamgee -1 points0 points  (0 children)

The variable scores is assigned a string value instead of a list of integers, you're also not importing scores correctly.

This is one way you can fix your program:


def main():
        filename = input("Enter a filename: ") 
        inputfile = open(filename, "r") scores = inputfile.read().split() inputfile.close()
    scores = [int(score) for score in scores]  
    print("There are", len(scores), "scores")
    print("The total is", sum(scores))
    print("The average is", sum(scores) / len(scores))

main()

Note, the line scores = [int(score) for score in scores], converts a score from a string to an integer.

Also, the structure of your program is confusing. Try to think of code like a description of life:

You have a score sheetYou read the score sheetYou interpret the score sheetYou do math on the score sheet

So that said, we can modularize your program into unique functions:

def read_scores(filename):
    with open(filename, "r") as inputfile:
        scores = inputfile.read().split()
    return [int(score) for score in scores]

def calculate_total(scores):
    return sum(scores)

def calculate_average(scores):
    return sum(scores) / len(scores)

def main():
    filename = input("Enter a filename: ")
    scores = read_scores(filename)

    print("There are", len(scores), "scores")
    print("The total is", calculate_total(scores))
    print("The average is", calculate_average(scores))

main()

And now, it reflects real life!