104k views
2 votes
How can the output of the top 5 scores from a .txt file in Python be formatted to display each score on a separate line?

A) Use the `print()` function with each score as an argument
B) Utilize the `split()` method to separate scores
C) Apply the `readlines()` method to the file object
D) Implement a loop to iterate through each score and print them individually

User Jbr
by
8.6k points

1 Answer

7 votes

Final answer:

To display the top 5 scores from a .txt file in Python on separate lines, you can use a loop to iterate through each score and print them individually.

Step-by-step explanation:

The correct answer is D) Implement a loop to iterate through each score and print them individually. To achieve this, you can read the scores from the .txt file using the readlines() method, which returns a list of lines. Then, you can sort the scores in descending order and use a loop to print the top 5 scores on separate lines. Here's an example:

scores = [95, 87, 78, 92, 84, 96, 89] # Assuming these are the scores from the file

scores.sort(reverse=True) # Sort the scores in descending order

for i in range(5): # Iterate over the first 5 scores
print(scores[i]) # Print each score on a separate line
User Vijayender
by
8.1k points