110k views
5 votes
#A certain CS professor gives 5-point quizzes that are graded on the scale

#5-A, 4-B, 3-C, 2-D, 1-F, 0-F. Wirte a program that accepts a quiz score
#as an input and prints out the corresponding grade.
def main():
grade = eval(input("What is your quiz score? (Type quit to stop) "))
if grade == 5:
letter = 'A'
if grade == 4:
letter = 'B'
if grade == 3:
letter = 'C'
if grade == 2:
letter = 'D'
if grade == 1 or grade == 0:
letter = 'F'
print(" Your grade is a ", letter)
main()

1 Answer

3 votes
The program you provided will work as intended, it prompts the user to enter a quiz score and assigns a letter grade based on the score. However, there are a few ways to improve the code:

Instead of using multiple 'if' statements, you can use 'elif' statements, which will check the condition only if the previous 'if' statement's condition is False.
You can use a dictionary to store the mapping of quiz scores to letter grades, this will make the code more readable and easier to maintain.
You can use a while loop to keep prompting the user for quiz scores until they enter 'quit'.
You can also add some validation code to check that the input is a number between 0 and 5, and prompt the user again if it is not.
Here is an example of how the improved code could look like:


def main():
grades = {5: 'A', 4: 'B', 3: 'C', 2: 'D', 1: 'F', 0: 'F'}
while True:
score = input("What is your quiz score? (Type quit to stop) ")
if score == 'quit':
break
if not score.isnumeric() or int(score) not in grades:
print("Invalid input. Please enter a number between 0 and 5.")
continue
print("Your grade is a", grades[int(score)])

main()
User Brian Anderson
by
7.8k points