I'm here not with a question of specific coding, but more of a query on how to generate specific variable outputs without using if statements.
To make it clearer here is an example: Mr. Smith is giving out 5 point quizzes that are graded on a scale of 5-A, 4-B, 3-C, 2-D, 1-E, 0-F. Create a program which accepts a the quiz score (1-5) as an input and prints out the corresponding grade without using if statements.
So hopefully that makes my dilemma much clearer. I'm looking for a way to associate the grade (A-F) with the corresponding quiz score (1-5) without using an if statement. I'm still fairly new to python and you could call me a slow learner but any help is appreciated!
The most straightforward and flexible way is to use a dictionary:
>>> score_grade_mapping = {6: 'A+', 5: 'A', 4: 'B', 3: 'C', 2: 'D', 1: 'E', 0: 'F'}
>>> score_grade_mapping[4]
'B'
>>> score_grade_mapping[6]
'A+'
While it is just a sequence of numbers, starting at zero, mapping to individual letters, you can do this more efficiently (though less obviously) with a string, using string indexing.
>>> score_grade_mapping = 'FEDCBA'
>>> score_grade_mapping[4]
'B'
If you needed more than a single letter, but still with a series of scores from zero onwards, you could use a list (mutable) or tuple (immutable, thus more efficient for such things where you are not changing it) with indexing:
>>> score_grade_mapping = 'F', 'E', 'D', 'C', 'B', 'A', 'A+'
>>> score_grade_mapping[4]
'B'
>>> score_grade_mapping[6]
'A+'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With