11.1 - High score

Problem

Write a program that will find the highest score in an array and write the value to a text file.

Scores array

scores = [56,98,100,34,65]

Expected answer.txt

The high score is 100
1 Find high score IN score
OUT high_score
2 Write high score to file IN high_score
OUT  

 

1.1  SET high_score TO scores[0]  
1.2  FOR i FROM 1 TO length(scores) - 1 DO  
1.3      IF scores[i] > high_score THEN  
1.4          SET high_score TO scores[i]  
1.5      END IF  
1.6  END FOR  
1.7  RETURN high_score  

3.1  OPEN file "answer.txt" FOR writing  
3.2  WRITE "The high score is " TO file  
3.3  WRITE high_score TO file  
3.4  CLOSE file

 

 

 

# Main
scores = [56,98,100,34,65]
high_score = find_high_score(scores)
write_data(high_score)
def find_high_score(scores):
    high_score = scores[0]
    for i in range(1, len(scores)):
        if scores[i] > high_score:
            high_score = scores[i]
    return high_score

def write_data(high_score):
    file = open("answer.txt", "w")
    file.write("The high score is ")
    file.write(str(high_score))
    file.close()

# Main
scores = [56,98,100,34,65]
high_score = find_high_score(scores)
write_data(high_score)
def find_high_score(scores):               # Defines a procedure to find the highest score
    high_score = scores[0]                 # Start by assuming the first score is the highest
    for i in range(1, len(scores)):        # Loop through the rest of the scores
        if scores[i] > high_score:         # If a higher score is found
            high_score = scores[i]         # Update the highest score
    return high_score                      # Return the final highest score

def write_data(high_score):                # Defines a procedure to write the high score to a file
    file = open("answer.txt", "w")         # Opens or creates a text file for writing
    file.write("The high score is ")       # Writes a message to the file
    file.write(str(high_score))            # Writes the high score as text
    file.close()                           # Closes the file to save changes

# Main
scores = [56,98,100,34,65]                 # An array of example scores
high_score = find_high_score(scores)       # Finds the highest score in the array
write_data(high_score)                     # Writes the high score to the file

Extension

Update the program to write the highest and lowest scores to file.

Target

Write variables to text file