How to use dictionaries

Asked 2 years ago, Updated 2 years ago, 44 views

Score credit

81~100 A

61~80 B

41~60 C

21~40 D

0~20 E

score: 83
grade is A

You want to represent the format of . We can solve the problem with the if, elif syntax, but we tried to make it using dictionary method
So, in order to get credit with the value through the key value,

user_in = input('score:')

grade = { tuple(range(81,101)): 'A' , tuple(range(61,81)):'B'..... } 

if user_in in grade.keys():

  expressed in the form of print ('grade is', grade[user_in]).

I put in the tuple value because I heard that I have to put a value that does not change in the key value, but I get an error. I'm not sure what's wrong with me, so I'm posting it here for help... ...if it doesn't work as a dictionary, I'd really appreciate it if you could tell me more about the other options. I just started Python, so please give me more details

python3 error

2022-09-21 11:56

3 Answers

tbl = { -1:'E', 0:'E', 1:'D', 2:'C', 3:'B', 4:'A' }
user_in = int(input('your score'))
print('your grade is ', tbl[(user_in-1)//20])


2022-09-21 11:56

There is also an implementation method using the ASKI code.

user_in = int(input('score:'))
print('E' if (user_in is 0) else (chr(69 - (user_in - 1) // 20)))


2022-09-21 11:56

You can also use the range function.

>>> d = dict(zip(range(-1, 10), ('E', 'E', 'D', 'C', 'B', 'A')))
>>> d
{-1: 'E', 0: 'E', 1: 'D', 2: 'C', 3: 'B', 4: 'A'}


2022-09-21 11:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.