Checkpoint 10.5.1.
Let’s work to improve the formatting of the sentence produced by the program above. Revise the following code so that it outputs the sentence:
The scores are 85, 95, and 70.
Hint.
Try changing the loop so that it does not process the final score. Handle that last score separately, after the loop finishes.
Solution.
scores = [85, 95, 70]
result = ''
for score in scores[:-1]:
result = result + str(score) + ', '
# Now, append the last score
result = result + 'and ' + str(scores[-1]) + '.'
print("The scores are " + result)
This solution works by iterating over all of the scores in the list except the last, and dealing with that one separately.