Why is there a key error?

Asked 2 years ago, Updated 2 years ago, 18 views

id = str("Enter user ID: "))
b = int (input ("user's password input: ")))

dic = {'conan':1111 , 'rose':2222 , 'ran':3333}
passward = dic[id]

if id in dic:        
    if passward == b:
        print("You have successfully logged in".")
    else:
        print("The password is invalid.")
else:
    print("Not a registered user". Check your membership information.")

Reason why keyerror occurs when a value other than the value inside dictionary is entered in id

Enter user's ID: ccc
Enter user's password: 1111
Traceback (most recent call last):
  File "C:\Users\82109\Desktop\Login Program.py", line 8, in <module>
    passward = dic[id]
KeyError: 'ccc'

python

2022-09-22 20:20

1 Answers

>>> a = {1: 'a'}
>>> a[2] = 'b'
>>> a
{1: 'a', 2: 'b'}

When 'ccc' approached the value without dic['ccc'] in the dictionary where the key does not exist, There is a key error, and the password allocation statement cannot be established.

Do not initialize y first If x = y then there is an error...

And since all return values of input statements are processed as strings, there is no need to convert them from id to str.


2022-09-22 20:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.