9618/41

Computer Science 9618/41May/June 2022

Cambridge A-Level · Practical · worked solutions for every part, with the mark scheme

3
questions
75
marks
150
minutes

Topics Programming Paradigms (Procedural and Object-oriented) · Algorithms and Abstract Data Types · File Processing and Exception Handling

Q1Programming Paradigms (Procedural and Object-oriented)File Processing and Exception HandlingAlgorithms and Abstract Data TypesFree sample

Open the document evidence.doc

Make sure that your name, centre number and candidate number will appear on every page of this document. This document must contain your answers to each question.

Save this evidence document in your work area as:

evidence_ followed by your centre number_candidate number, for example: evidence_zz999_9999

A class declaration can be used to declare a record.
If the programming language used does not support arrays, a list can be used instead.

A source file is used to answer question 1. The file is called HighScore.txt

The text file HighScore.txt stores the players who have scored the top ten scores in a game, in descending order of score. The file stores the 3-character name of the player, and their integer score, in the order: player, score.

For example, the current top player in the text file:

FYI is the player name

10000 is the score

The program:

  • reads in the data from HighScore.txt
  • allows the user to enter a new player name and their score
  • if appropriate, inserts the new player (name and score) into the top ten
  • writes the top ten players (name and score) into a new text file NewHighScore.txt
(a)

The program stores the players and their scores in an array of 11 elements (10 elements to be read from the file, 1 element to be inserted by the user).

Write a program to declare one or more arrays, as global data structures, to store the player names and their scores.

Save your program as Question1_J2022.

Copy and paste the program code into part 1(a) in the evidence document.

2M
DifficultyMedium-Easy
Worked solution

Answer

PlayerName = [""] * 11
PlayerScore = [0] * 11
Final answer

See program code

Detailed explanation

Background Concept

A global data structure is declared outside any procedure or function so that all parts of the program can access it. In this task, each player has two related pieces of data: a 3-character name and an integer score. A common practical way to store this is with two parallel arrays or lists, where the same index in both structures refers to the same player.

Because the question says there are 10 scores read from the file and 1 extra space for a possible new score, each structure must have 11 elements.

Understanding the Question

You are asked only to declare the data structures, not to read or display anything yet. The important clues are:

  • they must be global
  • they must store names and scores
  • they must hold 11 items in total
  • the language may use arrays or lists

In Python, lists are the natural choice.

Approach

Use two parallel global lists:

  • one for player names, initialised with empty strings
  • one for scores, initialised with zeros

This keeps the code simple for later parts, because reading, outputting, inserting and writing can all use the same index in both lists.

Step-by-Step Reasoning

PlayerName = [""] * 11

  • creates a list of 11 string elements
  • each element starts as an empty string
  • this is suitable for storing 3-character player names later

PlayerScore = [0] * 11

  • creates a list of 11 integer elements
  • each element starts at 0
  • this is suitable for storing numeric scores

The two lists are global because they are declared at the top level, outside any procedure.

Index 0 in PlayerName matches index 0 in PlayerScore, index 1 matches index 1, and so on.

Key Takeaways

  • Global structures are useful when several procedures must work on the same data.
  • Parallel arrays/lists store related fields using the same index.
  • Always match the declared size to the maximum number of items required.

Common Mistakes

  • Declaring only 10 elements instead of 11.
  • Using just one list, but not storing both the name and score properly.
  • Declaring the structures inside a procedure, which would make them local rather than global.
  • Storing scores as strings instead of integers.

Things to Be Careful About

  • The extra slot is important because the new player may need to be inserted before the list is reduced back to the top ten.
  • The names and scores must stay aligned by index throughout the whole program.
  • In Python, lists are acceptable here even though the question uses the word array.
Techniques used
declare global arraysallocate fixed-size storage for parallel dataseparate player names from integer scores
(b)

The procedure ReadHighScores() opens the file HighScore.txt and reads the data into the data structure(s) declared in part 1(a).

Write program code to declare the procedure ReadHighScores().

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

6M
DifficultyMedium
Worked solution

Answer

def ReadHighScores():
    with open("HighScore.txt", "r") as file:
        for Index in range(10):
            PlayerName[Index] = file.readline().strip()
            PlayerScore[Index] = int(file.readline().strip())
Final answer

See program code

Detailed explanation

Background Concept

A sequential text file is read from the beginning to the end, one item after another. Here, the file stores data in a repeated pattern:

  • one line for the player name
  • one line for the score

So each player record takes two lines. When reading this kind of file, the program must keep the two reads together so that the name and score go into matching positions in the arrays.

Understanding the Question

This part asks for a procedure called ReadHighScores() that opens HighScore.txt and loads the existing top ten into the global structures declared in part (a). From the source file, there are 10 players, so the loop must run 10 times. Each iteration must read:

  1. the player name
  2. the score

Then it must store them in the same index.

Approach

Use a with open(..., "r") block to open the file safely for reading. Then loop from 0 to 9. On each pass:

  • read one line for the name
  • read the next line for the score
  • strip the newline from both
  • convert the score to int
  • store both in the parallel lists

Step-by-Step Reasoning

def ReadHighScores():

  • defines the required procedure

with open("HighScore.txt", "r") as file:

  • opens the file in read mode
  • the with statement also closes it automatically afterwards

for Index in range(10):

  • repeats exactly 10 times, once for each existing high score entry
  • valid list positions are 0 to 9

PlayerName[Index] = file.readline().strip()

  • reads the next line from the file
  • removes the trailing newline
  • stores the player name in the current position

PlayerScore[Index] = int(file.readline().strip())

  • reads the following line, which contains the score
  • removes the newline
  • converts the text to an integer
  • stores it in the matching score list position

For example, on the first iteration:

  • name read: FYI
  • score read: 10000
  • stored in PlayerName[0] and PlayerScore[0]

Then the second iteration stores ABC and 9092, and so on.

Key Takeaways

  • Sequential files are read in order.
  • When a record spans multiple lines, keep the reads grouped correctly.
  • Convert numeric text to an integer before storing if later processing needs arithmetic or comparisons.

Common Mistakes

  • Reading only one line per loop iteration, which misaligns the data.
  • Forgetting to convert the score from string to integer.
  • Looping 11 times instead of 10 and reading beyond the file data.
  • Storing the name and score at different indexes.

Things to Be Careful About

  • .strip() is important because file lines usually end with \n.
  • The extra 11th element is not read from the file; it is reserved for the possible new entry.
  • Keep the filename exactly as HighScore.txt.
Techniques used
open a text file for readingread sequential pairs of linesconvert score text to integerstore values by indexed assignment
(c)

The procedure OutputHighScores() outputs all the values in the data structure(s) in the format:

PlayerName Score

For example, the first two data items:

FYI 10000
ABC 9092

Write program code to declare the procedure OutputHighScores().

Save your program.

Copy and paste the program code into part 1(c) in the evidence document.

3M
DifficultyMedium-Easy
Worked solution

Answer

def OutputHighScores():
    for Index in range(10):
        print(PlayerName[Index], PlayerScore[Index])
Final answer

See program code

Detailed explanation

Background Concept

An output procedure takes data already stored in memory and displays it in a required format. When data is held in parallel arrays, the same index is used to access the related values together. So if PlayerName[3] is PAI, then PlayerScore[3] should be that same player's score.

Understanding the Question

You must declare a procedure called OutputHighScores() that displays the stored entries as:

PlayerName Score

The example shows one player per line, with a space between the name and score. Since the top ten list contains 10 valid entries, the loop should output the first 10 positions.

Approach

Use a loop from 0 to 9 and print the corresponding name and score together on each pass. In Python, print(value1, value2) automatically separates them with a space, which matches the required format.

Step-by-Step Reasoning

def OutputHighScores():

  • defines the required procedure

for Index in range(10):

  • loops through the 10 top-score entries
  • does not use the extra slot at index 10

print(PlayerName[Index], PlayerScore[Index])

  • outputs the name and score from the same position
  • Python prints them with a space between them
  • each print() ends with a newline, so each player appears on a separate line

For example, when Index is 0, the output is:
FYI 10000

When Index is 1, the output is:
ABC 9092

Key Takeaways

  • Parallel arrays are output by using the same index in both structures.
  • A simple count-controlled loop is enough when the number of items is known.
  • Always match the output format exactly to the question.

Common Mistakes

  • Looping through 11 items and printing the unused extra element.
  • Printing names first and then scores in a separate loop, which breaks the pairing.
  • Forgetting the space between the name and score.
  • Outputting commas or brackets instead of plain text lines.

Things to Be Careful About

  • The required output is one player per line.
  • Only the top ten should be displayed, not the spare insertion slot.
  • The data must already have been read before this procedure is called.
Techniques used
iterate through parallel arraysformat console output as name and scoreoutput only the top ten entries
(d)

The main program should first call ReadHighScores() and then OutputHighScores().

(i)

Write the program code for the main program.

Save your program.

Copy and paste the program code into part 1(d)(i) in the evidence document.

2M
DifficultyEasy
Worked solution

Answer

if __name__ == "__main__":
    ReadHighScores()
    OutputHighScores()
Final answer

See program code

Detailed explanation

Background Concept

The main program controls the order in which procedures run. In a procedural solution, you normally:

  1. set up or read the data
  2. process it
  3. output the result

Calling procedures in the right sequence is essential, because later procedures often depend on earlier ones having already prepared the data.

Understanding the Question

This part says the main program should first call ReadHighScores() and then OutputHighScores(). That means the stored values must be loaded from the file before attempting to print them.

Approach

Write a minimal Python main block that:

  • starts program execution
  • reads the file into the arrays
  • outputs the values that were read

Step-by-Step Reasoning

if __name__ == "__main__":

  • marks the main program section in Python
  • ensures this code runs when the program is executed directly

ReadHighScores()

  • must come first
  • fills the arrays with the ten player names and scores from the file

OutputHighScores()

  • comes second
  • uses the data now stored in the arrays and prints it in the required format

If these were reversed, the output procedure would run before the arrays had been populated, so the results would be incorrect.

Key Takeaways

  • Main programs organise the order of execution.
  • Input or file reading usually comes before output.
  • A procedure call is only useful if the required data is already available.

Common Mistakes

  • Calling OutputHighScores() before ReadHighScores().
  • Omitting one of the procedure calls.
  • Writing the procedures again instead of just calling them.

Things to Be Careful About

  • The question is about the main program only, not the full program listing again.
  • Keep the call order exactly as stated.
  • Make sure the procedure names match earlier declarations exactly.
Techniques used
call procedures in sequencestructure a simple main program
(ii)

Test your program.

Take a screenshot to show the output from part 1(d)(i).

Copy and paste the screenshot into part 1(d)(ii) in the evidence document.

1M
DifficultyEasy
Worked solution

Answer

Input file used: HighScore.txt

FYI 10000
ABC 9092
KEL 8500
PAI 8203
BBB 7980
ACE 7246
GKL 7001
JSI 6490
EIF 6003
DIS 2000
Final answer

See expected console output

Detailed explanation

Background Concept

A test run for a program that reads a file and prints values can be predicted exactly if the input file contents are known. Since this question gives the full contents of HighScore.txt, the expected output can be worked out without ambiguity.

Understanding the Question

You are testing the main program from part (d)(i). That main program:

  1. reads the 10 players and scores from the file
  2. outputs them in the format PlayerName Score

So the screenshot should simply show the ten lines from the file, paired correctly.

Approach

Take the file two lines at a time:

  • first line is the player name
  • second line is the score

Then write each pair on one output line.

Step-by-Step Reasoning

From the file:

  • FYI and 10000 become FYI 10000
  • ABC and 9092 become ABC 9092
  • KEL and 8500 become KEL 8500
  • PAI and 8203 become PAI 8203
  • BBB and 7980 become BBB 7980
  • ACE and 7246 become ACE 7246
  • GKL and 7001 become GKL 7001
  • JSI and 6490 become JSI 6490
  • EIF and 6003 become EIF 6003
  • DIS and 2000 become DIS 2000

Because the main program in part (d)(i) has no user input prompts, the console output contains only these ten lines.

Key Takeaways

  • When a file is fully provided, you can derive exact test output.
  • Parallel arrays should preserve the correct pairing between fields.
  • Testing often checks both the content and the formatting of output.

Common Mistakes

  • Forgetting that the score is printed on the same line as the name.
  • Printing blank lines because the file newline was not stripped.
  • Including an extra unused 11th element.

Things to Be Careful About

  • The order must stay descending, exactly as stored in the file.
  • There are no prompts or extra headings in this specific test run.
  • The output must contain ten entries, not nine or eleven.
Techniques used
trace the program using the given file dataformat the resulting console output
(e)

The main program needs to ask the user to input a new player name and a score. If this score is in the top ten then it will create a new top ten list that includes this score.

(i)

Amend the main program to ask the user to input a 3-character player name and an integer score that must be between 1 and 100 000 inclusive.

Save your program.

Copy and paste the program code into part 1(e)(i) in the evidence document.

3M
DifficultyMedium-Easy
Worked solution

Answer

if __name__ == "__main__":
    ReadHighScores()
    OutputHighScores()
    NewPlayer = input("Enter username\n")
    while len(NewPlayer) != 3:
        NewPlayer = input("Enter username\n")
    NewScore = int(input("Enter score\n"))
    while NewScore < 1 or NewScore > 100000:
        NewScore = int(input("Enter score\n"))
Final answer

See program code

Detailed explanation

Background Concept

Input validation checks whether data meets required rules before the program continues. Two common types appear here:

  • length validation for the player name
  • range validation for the score

Validation is important because later parts of the program assume the name is exactly 3 characters and the score is a valid integer within the allowed limits.

Understanding the Question

You are asked to amend the main program so that it asks for:

  • a 3-character player name
  • an integer score from 1 to 100000 inclusive

This does not yet require insertion; it only requires collecting valid input ready for later use.

Approach

Keep the existing main program structure, then add:

  1. an input for the player name
  2. a loop that repeats until the name length is exactly 3
  3. an input for the score
  4. a loop that repeats until the score is inside the allowed range

Step-by-Step Reasoning

ReadHighScores() and OutputHighScores() remain from the earlier main program.

NewPlayer = input("Enter username\n")

  • asks the user to type a player name
  • the newline in the prompt makes the typed value appear on the next line

while len(NewPlayer) != 3:

  • checks the name length
  • repeats the prompt if the name is not exactly 3 characters

NewScore = int(input("Enter score\n"))

  • asks for the score
  • converts the typed text into an integer

while NewScore < 1 or NewScore > 100000:

  • checks that the score is within the inclusive range
  • repeats the prompt if it is too small or too large

Once both values are valid, they are stored in NewPlayer and NewScore for later use.

Key Takeaways

  • Validation ensures input satisfies the rules before processing.
  • Exact-length checks and range checks are very common exam patterns.
  • Store validated input in variables ready for later procedures.

Common Mistakes

  • Checking <= 3 or >= 3 instead of exactly 3 characters.
  • Using the wrong score limits.
  • Forgetting that the range is inclusive, so 1 and 100000 are both valid.
  • Not converting the score to int.

Things to Be Careful About

  • This code assumes the user enters numeric text for the score; handling non-numeric errors is a separate issue unless specifically asked.
  • Use the same variable names later when calling the insertion procedure.
  • Do not lose the earlier file-reading step when amending the main program.
Techniques used
prompt for keyboard inputvalidate string lengthvalidate numeric rangestore accepted input for later processing
(ii)

Write program code to declare a procedure that:

  • takes the player name and score as parameters
  • creates a new top ten list that includes the parameter if appropriate.

Save your program.

Copy and paste the program code into part 1(e)(ii) in the evidence document.

5M
DifficultyMedium
Worked solution

Answer

def InsertScore(NewPlayerName, NewPlayerScore):
    PlayerName[10] = NewPlayerName
    PlayerScore[10] = NewPlayerScore
    for Index in range(10, 0, -1):
        if PlayerScore[Index] > PlayerScore[Index - 1]:
            TempScore = PlayerScore[Index - 1]
            PlayerScore[Index - 1] = PlayerScore[Index]
            PlayerScore[Index] = TempScore
            TempName = PlayerName[Index - 1]
            PlayerName[Index - 1] = PlayerName[Index]
            PlayerName[Index] = TempName
Final answer

See program code

Detailed explanation

Background Concept

This is an insertion into a sorted list. The scores are already stored in descending order, so the new score should be placed into the spare 11th position and then moved upward until it reaches the correct place. Because the player name and score are related, any movement of a score must also move the matching name.

This is similar to one backward pass of bubble sort or an insertion operation in a sorted array.

Understanding the Question

The procedure must:

  • take a player name and score as parameters
  • create a new top-ten list if the score is good enough

The question has already provided an 11-element structure, so the intended method is to use the extra slot for the new value and then reorder the list.

Approach

  1. Put the new name and score into index 10, the spare slot.
  2. Move backwards through the list.
  3. Whenever the new score is greater than the score above it, swap them.
  4. Whenever scores are swapped, also swap the corresponding names.

After this pass, the list is still in descending order, and the lowest item ends up in the unused last position.

Step-by-Step Reasoning

def InsertScore(NewPlayerName, NewPlayerScore):

  • defines the procedure with the required parameters

PlayerName[10] = NewPlayerName
PlayerScore[10] = NewPlayerScore

  • place the new entry into the extra slot

for Index in range(10, 0, -1):

  • starts at the last position and moves backwards to 1
  • compares each item with the one above it

if PlayerScore[Index] > PlayerScore[Index - 1]:

  • checks whether the lower item should move up because its score is higher
  • this maintains descending order

The temporary variables perform a swap:

  • first swap the scores
  • then swap the names

Swapping both arrays is essential, otherwise names and scores would no longer match.

If the new score is too small, no swap happens, so it stays in the 11th slot and is effectively ignored when only the top ten are later output or written to file.

Key Takeaways

  • A sorted list can accept a new item by inserting it and shifting or swapping into place.
  • Parallel arrays must always be updated together.
  • Working backwards is a natural way to insert into a descending list with one spare slot.

Common Mistakes

  • Swapping scores but forgetting to swap names.
  • Comparing in the wrong direction, which would produce ascending order.
  • Starting at the wrong index and missing the spare slot.
  • Using only 10 elements, leaving nowhere to place the new value temporarily.

Things to Be Careful About

  • Index 10 is the 11th element in Python because indexing starts at 0.
  • The list is descending, so higher scores move towards the front.
  • Equal scores are not moved by this version because the test uses > rather than >=, which keeps the existing order stable enough for this task.
Techniques used
pass name and score as parametersplace a new item in the spare array slotcompare adjacent scores in descending orderswap paired name and score values
(iii)

Amend the main program to call the procedure from part 1(e)(ii).

Output the contents of the array before inserting the new player name and score, and output the contents of the array after inserting the new player name and score.

Save your program.

Copy and paste the program code into part 1(e)(iii) in the evidence document.

2M
DifficultyMedium-Easy
Worked solution

Answer

if __name__ == "__main__":
    ReadHighScores()
    NewPlayer = input("Enter username\n")
    while len(NewPlayer) != 3:
        NewPlayer = input("Enter username\n")
    NewScore = int(input("Enter score\n"))
    while NewScore < 1 or NewScore > 100000:
        NewScore = int(input("Enter score\n"))
    print("before")
    OutputHighScores()
    InsertScore(NewPlayer, NewScore)
    print("after")
    OutputHighScores()
Final answer

See program code

Detailed explanation

Background Concept

A main program often acts as the coordinator for a series of smaller procedures. Good decomposition means each procedure does one job:

  • ReadHighScores() loads the data
  • OutputHighScores() displays the current list
  • InsertScore() updates the list structure

The main program decides when each one runs.

Understanding the Question

This part asks you to amend the main program again so that it:

  • asks for the new player name and score
  • outputs the current list before insertion
  • calls the insertion procedure
  • outputs the list after insertion

So the important idea is not just calling the procedure, but showing the effect of the procedure clearly.

Approach

Use this order:

  1. read the original top ten from file
  2. input and validate the new values
  3. print before
  4. output the original list
  5. call InsertScore()
  6. print after
  7. output the updated list

Step-by-Step Reasoning

ReadHighScores()

  • loads the original ten entries into the arrays

The input and validation code stores valid values in NewPlayer and NewScore.

print("before")

  • labels the first output clearly

OutputHighScores()

  • shows the original top ten before any change

InsertScore(NewPlayer, NewScore)

  • passes the newly entered values into the insertion procedure
  • the procedure updates the global arrays into the new sorted order

print("after")

  • labels the second output

OutputHighScores()

  • shows the updated top ten after the insertion logic has been applied

This ordering makes it easy to verify that the procedure worked correctly.

Key Takeaways

  • Main programs integrate smaller procedures into a complete solution.
  • Printing data before and after an update is a strong testing technique.
  • Parameter passing allows the main program to supply user input to a procedure.

Common Mistakes

  • Printing only after insertion and forgetting the before output.
  • Calling InsertScore() before showing the original list.
  • Not passing both the player name and score as parameters.
  • Losing the validation code from part (e)(i).

Things to Be Careful About

  • The labels before and after should be output in the correct places.
  • The arrays must be read from the file before the insertion is attempted.
  • Keep the order of procedure calls logical and consistent.
Techniques used
call procedures in sequenceoutput the list before processingpass input values to a procedureoutput the updated list after processing
(iv)

Test your program by entering the player name "JKL" and the score "9999".

Take a screenshot to show the output.

Copy and paste the screenshot into part 1(e)(iv) in the evidence document.

1M
DifficultyMedium-Easy
Worked solution

Answer

Inputs used: JKL and 9999

Enter username
JKL
Enter score
9999
before
FYI 10000
ABC 9092
KEL 8500
PAI 8203
BBB 7980
ACE 7246
GKL 7001
JSI 6490
EIF 6003
DIS 2000
after
FYI 10000
JKL 9999
ABC 9092
KEL 8500
PAI 8203
BBB 7980
ACE 7246
GKL 7001
JSI 6490
EIF 6003
Final answer

See expected console output

Detailed explanation

Background Concept

Testing a sorted insertion routine means checking both the original state and the updated state. Because the list is in descending order, a higher score must appear nearer the top. If a new score is inserted into the top ten, the lowest previous score is pushed out of the visible list.

Understanding the Question

The test data is fixed:

  • player name: JKL
  • score: 9999

You must show the expected output of the amended main program from part (e)(iii), which prints:

  • the prompt and entered values
  • the list before insertion
  • the list after insertion

Approach

Compare 9999 with the existing scores:

  • less than 10000
  • greater than 9092

So JKL 9999 must be inserted into second place.

Then everything below that position shifts down by one place, and the old last visible top-ten entry is removed from the displayed list.

Step-by-Step Reasoning

Original list:

  1. FYI 10000
  2. ABC 9092
  3. KEL 8500
  4. PAI 8203
  5. BBB 7980
  6. ACE 7246
  7. GKL 7001
  8. JSI 6490
  9. EIF 6003
  10. DIS 2000

Now insert JKL 9999.

Since 9999 is less than 10000 but greater than 9092, it goes between those two. The updated top ten becomes:

  1. FYI 10000
  2. JKL 9999
  3. ABC 9092
  4. KEL 8500
  5. PAI 8203
  6. BBB 7980
  7. ACE 7246
  8. GKL 7001
  9. JSI 6490
  10. EIF 6003

DIS 2000 is pushed into 11th place, so it is no longer shown when only the top ten are output.

Key Takeaways

  • In a descending list, compare the new score against existing scores to locate its position.
  • Showing before and after output is an effective test of insertion logic.
  • When a list is limited to the top ten, the lowest previous item may be dropped.

Common Mistakes

  • Putting JKL 9999 in first place even though 10000 is higher.
  • Leaving DIS 2000 in the output after insertion, which would incorrectly show 11 items.
  • Forgetting the before section and showing only the final list.

Things to Be Careful About

  • The program prompts appear before the lists.
  • The output remains in descending order after insertion.
  • The new player is inserted only once, not added again at the bottom as well.
Techniques used
use the given test datapredict the insertion position in a descending listtrace the before-and-after console output
(f)

The procedure WriteTopTen() stores the new top ten player names and scores in a text file called NewHighScore.txt

Write program code to declare the procedure WriteTopTen().

Save your program.

Copy and paste the program code into part 1(f) in the evidence document.

4M
DifficultyMedium-Easy
Worked solution

Answer

def WriteTopTen():
    with open("NewHighScore.txt", "w") as file:
        for Index in range(10):
            file.write(PlayerName[Index] + "\n")
            file.write(str(PlayerScore[Index]) + "\n")
Final answer

See program code

Detailed explanation

Background Concept

Writing to a sequential text file means sending data out in a fixed order so that it can be read again later. The output format here must match the original input file format:

  • player name on one line
  • score on the next line
  • repeated for each of the top ten entries

If the format changes, a later reading procedure would not interpret the file correctly.

Understanding the Question

You must declare WriteTopTen() to store the new top ten in a file called NewHighScore.txt. The procedure needs to write only the top ten entries, not the spare 11th slot.

Approach

Open the file in write mode, loop through indexes 0 to 9, and for each index:

  1. write the player name followed by a newline
  2. write the score converted to a string followed by a newline

Step-by-Step Reasoning

def WriteTopTen():

  • defines the required procedure

with open("NewHighScore.txt", "w") as file:

  • opens the destination file in write mode
  • if the file already exists, it will be replaced
  • the file closes automatically at the end of the block

for Index in range(10):

  • writes the ten top-score entries only
  • ignores the extra temporary slot at index 10

file.write(PlayerName[Index] + "\n")

  • writes the player name on one line

file.write(str(PlayerScore[Index]) + "\n")

  • converts the integer score into text
  • writes it on the next line

After the loop finishes, NewHighScore.txt contains the new top-ten list in the same structure as HighScore.txt.

Key Takeaways

  • File output must preserve the required format exactly.
  • Integers must be converted to strings before writing text files in Python.
  • Only the top ten should be stored in the new file.

Common Mistakes

  • Writing 11 entries instead of 10.
  • Forgetting to convert the score to a string.
  • Writing name and score on the same line when the file format requires separate lines.
  • Using the wrong output filename.

Things to Be Careful About

  • The filename must be exactly NewHighScore.txt.
  • The line order matters: name first, then score.
  • A write-mode open replaces previous contents, which is appropriate here because the task is to create the new top-ten file.
Techniques used
open a text file for writingloop through the top ten entrieswrite paired values on separate linesconvert integers to strings for output

The rest of this paper

2 more questions
  • Q2Programming Paradigms (Procedural and Object-oriented)25M
  • Q3Programming Paradigms (Procedural and Object-oriented) · Algorithms and Abstract Data Types21M
Loading the full paper…