Creating multiple output variables without using if statements

I am not here with a question about specific coding, but rather about a query on how to generate certain variable outputs without using if statements.

To make this clearer, here is an example: Mr. Smith gives out 5-point quizzes that are rated on a scale of 5-A, 4-B, 3-C, 2-D, 1-E, 0- F. Create a program, which takes the quiz score (1-5) as input and displays the corresponding score without using if statements.

So hopefully this makes my dilemma much clearer. I am looking for a way to associate a grade (AF) with a corresponding quiz grade (1-5) without using an if statement. I'm still pretty new to python and you can call me a slow learner, but any help is appreciated!

+3
source share
3 answers

You can use:

'FEDCBA'[score]

This works by taking a character at a position scorein a string 'FEDCBA': Fis in position 0, Eis in position 1, etc.

For instance:

In [1]: 'FEDCBA'[0]
Out[1]: 'F'

In [2]: 'FEDCBA'[5]
Out[2]: 'A'
+3
source

The easiest and most 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+'

Although this is just a sequence of numbers, starting from zero, matching individual letters, you can do it more efficiently (although less obviously) with a string using string indexing .

>>> score_grade_mapping = 'FEDCBA'
>>> score_grade_mapping[4]
'B'

, , () (, , , ) :

>>> score_grade_mapping = 'F', 'E', 'D', 'C', 'B', 'A', 'A+'
>>> score_grade_mapping[4]
'B'
>>> score_grade_mapping[6]
'A+'
+6
Dictionary

:

dic={5:'A',4:'B',3:'C',2:'D',1:'E',0:'F'}
score=int(input())
grade=dic.get(score,'invalid input')
print(grade)
+2
source

All Articles