In: Computer Science
---- Python
CIMP 8A
Code Lab 4
Write a program that asks the user to enter 5 test scores. The program will display a letter grade for each test score and an average grade for the test scores entered. The program will write the student name and average test score to a text file (“studentgrades.txt”). Three functions are needed for this program.
def letter_grade( test_score)
Test Score |
Letter Grade |
90-100 |
A |
80-89 |
B |
70-79 |
C |
60-69 |
D |
Below 60 |
F |
return letter grade
def calculate_average_grade( test1, test2, test3, test4, test5)
add 5 test scores together with a sum
divide the sum by 5 for an average
return the average
def main() Starting function
In a loop for 4 students
Enter student name
In a loop for 5 test scores
enter test score
call letter_grade(test_score)
display testscore and letter grade
After loop
call calculate_average_grade (test1, test2, test3, test4, test5)
display average test score
write to output file –
name,
average test score and
letter grade for average test score
Code Screenshot :
Executable Code:
#Function to find the letter grade
def letter_grade(test_score):
if test_score <=100 and test_score>=90:
return 'A'
if test_score <=89 and test_score>=80:
return 'B'
if test_score <=79 and test_score>=70:
return 'C'
if test_score <=69 and test_score>=60:
return 'D'
if test_score <60:
return 'F'
#Function to calculate the average
def calculate_average_grade(test1, test2, test3, test4,
test5):
sum= test1+test2+test3+test4+test5
#Calculate average
average = sum/5
#Return result
return average
#Main Function
def main():
#Declaring the required
variables
test1=0
test2=0
test3=0
test4=0
test5=0
#Prompting the user for name
name = input("Please enter your name: ")
for i in range(5):
#Prompting the user for
test scores
test_score = int(input("Enter test
"+str(i+1)+" score: "))
print("Test Score
:",test_score,"Letter Grade:",letter_grade(test_score))
if i==0:
test1=test_score
elif i==1:
test2=test_score
elif i==2:
test3=test_score
elif i==3:
test4=test_score
elif i==4:
test5=test_score
#Find the average
average = calculate_average_grade(test1, test2, test3,
test4, test5)
#Display the average
print("Average: ",average)
#Open file
with open("studentgrades.txt","w") as f:
#Write name average and
lettergrade to file
f.write(name)
f.write("\nAverage Test Score
="+str(average))
f.write("\nLetter Grade
="+str(letter_grade(test_score)))
#Function call to main
main()
Sample Output :
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)