Noxbrand
Noxbrand

Reputation: 15

Looping test scores in file input/output

For my Programming assignment I had to

Create 2 programs using File input and output. The first program prompting the user to input 5 test scores, then write that to its own line in a file named tests.txt. The second program then reads tests.txt, displays all of the scores, and the average of the scores.

So I turned in the following code and got an okay-ish grade on it, with the following feedback:

I deducted points for poor design. When you find your code repeating almost similar lines, use a loop. You need a loop in both programs.

So, I'm stuck in the fact of cleaning up the design and putting a loop in them (although I thought that is what my For Loop was doing). Help and clarification would be very much appreciated =D

Here is the first program:

def main():
    score1=int(input("Please input your first score: "))
    score2=int(input("Please input your second score: "))
    score3=int(input("Please input your third score: "))
    score4=int(input("Please input your fourth score: "))
    score5=int(input("Please input your fifth score: "))

    score_file=open("tests.txt","w")

    for count in range(1, 5):
        score_file.write(str(score1) + "\n")
        score_file.write(str(score2) + "\n")
        score_file.write(str(score3) + "\n")
        score_file.write(str(score4) + "\n")
        score_file.write(str(score5) + "\n")

    score_file.close()

main()

Here is the second program:

def main():

    display_score=open("tests.txt", "r")
    for count in range(1,5):  
        score1=int(display_score.readline())
        score2=int(display_score.readline())
        score3=int(display_score.readline())
        score4=int(display_score.readline())
        score5=int(display_score.readline())

    display_score.close()

    average=(score1+score2+score3+score4+score5)/5

    print("Here are your scores you inputted: ", \
      score1, ", ",score2,", ",score3,", ",score4,", ",score5,\
      sep="")
    print("Your average is: ", average, "%",\
      sep="")

main()

Upvotes: 0

Views: 2149

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

Comments:

  • both your programs are actually wrong - your for loop reads 5 values, 5 times (for a total of 25 score entries)

  • whenever you find yourself with numbered variables (score1, score2, etc) it is usually a good sign you should be using a list

  • with is a better way to deal with files; it always ensures they get closed properly

  • str.format() (new-style string formatting) is usually faster and easier to read than string concatenation

Here is a simplified version of the first program

def main():
    with open("tests.txt", "w") as score_file:
        for tag in ["first", "second", "third", "fourth", "fifth"]:
            prompt = "Please input your {} score: ".format(tag)
            score  = int(input(prompt))
            output = "{}\n".format(score)
            score_file.write(output)

if __name__=="__main__":
    main()

which runs like

Please input your first score: 1
Please input your second score: 2
Please input your third score: 3
Please input your fourth score: 4
Please input your fifth score: 5

and of the second:

def average(lst):
    return float(sum(lst)) / len(lst)    

def main():
    with open("tests.txt") as score_file:
        scores = [int(line) for line in score_file]

    print("Here are your scores you inputted:")
    print(", ".join(str(score) for score in scores))

    print("Your average is: {}".format(average(scores)))

if __name__=="__main__":
    main()

which runs like

Here are your scores you inputted:
1, 2, 3, 4, 5
Your average is: 3.0

Upvotes: 1

furas
furas

Reputation: 142661

Reading scores:

all_scores = []

for x in range(5):
   all_score.append( int(input("score: ")) )

print all_scores

the same way you can write to file

for one_score in all_scores:
    score_file.write( str(one_score) + "\n")

but you can do it in one loop:

for x in range(5):
    score = input("score: ")
    score_file.write( score + "\n")

BTW: in first program you don't need to convert score to int() and then to str()

You can use for to add scores (or use special function sum(all_scores) for it)

sum_score = 0

for one_score in all_scores:
    sum_score = sum_score + one_score

print( sum_score / len(all_scores) )

len(all_scores) give you number of scores on the list

of course you can use for loop to read numbers from file

all_scores = []

for count in range(5):  
    all_scores.append( int(display_score.readline()) )

print( all_scores )

There is special function to print elements from list

print( ", ".join(all_scores) )

All values will be connected by ", "

Upvotes: 1

Related Questions