Previously I was doing a dictionary login and improving it. Everything is perfect, if I enter the username correctly but the password is wrong, it outputs an already established message and so far great. The problem comes if I put the user wrong first, the output is as follows:
Traceback (most recent call last):
File "pruebas.py", line 26, in <module>
x = usuarios[User]["apellido"]
KeyError: 'Loren'
The code is the following:
usuarios = {
"iperurena": {
"nombre": "Iñaki",
"apellido": "Perurena",
"password": "123123"
},
"fmuguruza": {
"nombre": "Fermín",
"apellido": "Muguruza",
"password": "654321"
},
"aolaizola": {
"nombre": "Aimar",
"apellido": "Olaizola",
"password": "123456"
}
}
User = input("Escriba su usuario: ")
Pass = input("Escriba su password: ")
x = usuarios[User]["apellido"]
intentos = 3
while(User != usuarios.keys() or Pass != usuarios[User]["password"]):
intentos -= 1
if intentos == 0:
break
print(f"Acceso fallido, te quedan {intentos} intentos")
User = input("Escriba su usuario: ")
Pass = input("Escriba su password: ")
if User in usuarios.keys() and Pass == usuarios[User]["password"]:
print(f"Bienvenido {User} {x}")
else:
print("Acceso fallido, te quedaste sin intentos")
The user "Loren" does not exist in the dictionary, causing the failure.
Before trying to access the dictionary, you have to make sure that the key exists, using
Second, the line
is wrong: you are comparing the string
User
with the listusuarios.keys()
. That doesn't make sense or logic.What you have to ask is
There are logic errors in the code that you can find when you fix the syntax problems.
The main problem is in the definition of
x
depends on what is entered in theinput()
ofUser
is contained in the dictionary. This is fixed by defining the variablex
within the validation that validates if both inputs are correct, that's where you needx
that forprint()
.Another observation worth making is the misuse you are giving to conditional structures, the
else
one at the end can be eliminated. This is because you have aif
within the main cycle that validates if the attempts are equal to 0. In said validation you can print the message on the screen.An additional note, it is much more comfortable to handle user data in a list. In the future, the validations will have to be done by iterating over the container of the dictionaries, the dictionaries are sets without order (you cannot iterate over them). It's just advice anyway, I don't know the needs or purposes of your script.
Implementing the above, your script can be more efficient if it is modified as follows:
Note: Of course with the dictionaries in the same file.
Finally, I enclose an execution by terminal, so that you can see the result obtained:
I hope it has served you, greetings!