The most common answer for the 5.2.8 Average Test Score CodeHS is:
total = 0
for i in range(3):
next = int(input("Enter a test score: "))
total = total + next
print("Average: " + str(total/3))
This code for calculating the average test score is almost correct, but there are a couple of improvements to be made for better clarity and accuracy:
- The print statement for the average should be placed outside the loop, so it only prints once after all scores are entered and summed.
- It’s good practice to use descriptive variable names. Instead of
For3Scores
andAverage
, names likescore
andtotal_score
might be more appropriate.
Here’s the revised version of the code:
import random
# Initialize variables
roll_count = 0
while True:
# Roll two dice
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll_count += 1
# Print the values rolled
print(f"Rolled: {die1} {die2}")
# Check for snake eyes (both dice are 1)
if die1 == 1 and die2 == 1:
break
# Output the total number of rolls
print(f"It took you {roll_count} rolls to get snake eyes.")
In this revised code:
- The loop iterates three times, each time asking for a score and adding it to
total_score
. - The average is calculated as
total_score / 3
and is printed after the loop completes. This ensures the average is only displayed once, after all the scores are entered. - Descriptive variable names are used for better readability.
Leave a comment