Home > Mobile >  Finding average of numbers in a .txt file with words and numbers
Finding average of numbers in a .txt file with words and numbers

Time:11-10

I have this code I'm working on and and option A and C work but when I press Option B I get an Error and I don't know how to fix it. The way it writes into the file is what I need it to be, it's just the extracting numbers and getting the average I struggle with. Here is the code I have:

loop = True

while loop:
    print("Welcome!\n Menu:\nA. Enter Player's Name and Golf Score\nB. Calculates Average Score\nC. Exits the program")
    choice = input("Enter you choice: ").lower()

    if choice == "a":
        name = input("Enter player's name: ")
        name = name.title()
        score = int(input("Enter players' score: "))

        while score < 18 or score > 150:
            score = int(input("Enter player's score again between 18 - 150: "))

        file = open("golf.txt", "a")
        file.write(f"{name}\n{score}\n")
        file.close()
        print("Added!\n")
    elif choice == "b":
        try:
            scores = []
            file1 = open("golf.txt", "r")
            # Reading every line in the file using readlines method
            lines = file1.readlines()
            # Looping through the lines
            for line in lines:
                # Extracting score from every line
                score = line.split()[1]
                # Appending the score in the scores list
                scores.append(int(score))
            file1.close()
            avg_score = round(sum(scores)/len(scores), 2)
            file2 = open("AverageScores.txt", "w")
            file2.write(f"{avg_score}")
            file2.close()
            print(avg_score)
        except:
            print("Error occurred")
    elif choice == "c":
        print('Bye!')
        loop = False
    else:
        print("Invalid choice")

I tried changing everything I know and I don't know what to do.

CodePudding user response:

If file is like following:

Bob
50
Bobba
25

Modify the reading loop for line in lines: to for line in lines[1::2]:

It will start from the index 1 and iterate by 2 instead by 1.

If the scores are always at the end of the line: Modify score = line.split()[1] to score = line.split()[-1] to get the last part of the line.

Don't forget that first element in list/tuple are at index 0: score = line.split()[0] to get the first word in the line (doesn't change from -1 if there is only one word).

  • Related