-1

partial code

if password_Dictionary[username] == password:
    print("Allow!\n")
    break
else:
    print("Wrong!\n")

error

if password_Dictionary[username] == password:
KeyError: 'cskmcdsk'

explanation

If the user inputs a username but not the correct passwordenter code here the program correctly runs a print statement that states user inputted wrong password, but when the user inputs an incorrect username/one that does not exist, it raises that 'KeyError' with 'cskmcdsk' being the random username the user tried inputting but it does not exist.

question

How would I stop the coding from causing an error and instead continue running and instead print an output that states that username is not in the dictionary?

QRuns
  • 1
  • 1
    you can use --> " if username in password_Dictionary " to check is this key available in the dictionary. if it returns false. then provide that key error – PushpikaWan Oct 27 '18 at 03:44
  • additionally you can wrap the "password_Dictionary[username] in a try except block, but you should only do this if it's an error, if this is an expected occurence, then Lucefer's answer is more apt. – TZubiri Oct 27 '18 at 03:50
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Oct 27 '18 at 04:22

2 Answers2

1

Don’t use a try/except block (exceptions are not for normal control flow). Instead, either check for the presence of the key in the dict, e.g.

if username in dictionary and dictionary[username] == password:
    # do stuff

or, alternatively, use dict.get which will return None, or some default (be certain to choose a default value which will not also be the value of the other side of the ==), e.g.

{}.get('notakey')         #=> None
{}.get('notakey', 'foo')  #=> 'foo'

As an aside, if you’re storing passwords, please ensure to use a strong one-way hash function (e.g. BCrypt).

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • @QRuns Well, did this answer your question? Don’t forget to [upvote/accept answers to your questions](http://meta.stackoverflow.com/a/5235/158402) `:)` – Andrew Marshall Oct 30 '18 at 13:04
-1

You can simply use try catch block for the key error, so when there is an error , you can catch it and do whatever you want when you catch a KeyError.

codejockie
  • 9,020
  • 4
  • 40
  • 46
  • No, you should use perfectly readable `.get(key, defaultvalue)`. `if key in dict:` rarely makes sense because you most likely were going to take out the value anyway too. using `KeyError` is just plain wrong, 4 lines minimum for what you could do in 1-2, while also adding unnecessary identation and making it less readable. – Purple Ice Oct 27 '18 at 10:06